英文:
Tailwindcss combine peer-focus-within with not(:peer-placeholder-shown)
问题
我想创建一个带有清除图标的输入字段,只有在输入焦点且占位符不可见时才显示。在项目中,我们在React中使用最新版本的tailwindcss。
我尝试使用not(:)运算符,但这不起作用。
这是问题的一个小示例:
function ExampleInput({
label,
className,
onClear,
...props
}: { label: string; onClear: () => void } & ComponentProps<'input'>) {
const id = useId();
return (
<div>
<label htmlFor={id}>
<span>{label}</span>
<input
{...props}
className={clsx('peer truncate text-lg/6', className)}
type="text"
id={id}
/>
<button
className="not(:peer-placeholder-shown):peer-focus-within:block absolute bottom-0.5 right-0.5 hidden text-spanishGrey"
type="button"
>
<CloseCrossIcon onClick={onClear} height="14" width="14" />
</button>
</label>
</div>
);
}
目标是只有在占位符隐藏且输入聚焦时才显示按钮,而且只使用CSS,也许可以使用自定义类或扩展tailwind主题。
英文:
I want to create a input field with an clear icon that only shows when the input is focused and the placeholder is not shown. In the project we use tailwindcss latest version in react.
I tried using the not(:) operator but this does not work.
Here is a small example of the problem:
function ExampleInput({
label,
className,
onClear,
...props
}: { label: string; onClear: () => void } & ComponentProps<'input'>) {
const id = useId();
return (
<div>
<label htmlFor={id}>
<span>{label}</span>
<input
{...props}
className={clsx('peer truncate text-lg/6', className)}
type="text"
id={id}
/>
<button
className="not(:peer-placeholder-shown):peer-focus-within:block absolute bottom-0.5 right-0.5 hidden text-spanishGrey"
type="button"
>
<CloseCrossIcon onClick={onClear} height="14" width="14" />
</button>
</label>
</div>
);
}
The goal would be that the button is only shown when the placeholder is hidden and the input is focused with only css. Maybe with a custom class or extension of the tailwind theme.
答案1
得分: 1
你可以考虑使用任意对等变体如 peer-[:not(:placeholder-shown):focus]
。还请注意,<input>
需要具有非空的 placeholder
属性值,以便匹配 :placeholder-shown
。
英文:
You could consider using an arbitrary peer variant like peer-[:not(:placeholder-shown):focus]
. Also note that the <input>
needs a non-empty placeholder
attribute value for :placeholder-shown
to match.
<!-- begin snippet: js hide: false console: false babel: false -->
<!-- language: lang-html -->
<script src="https://cdn.tailwindcss.com/3.3.3"></script>
<label>
<span>{label}</span>
<input class="peer" type="text" placeholder="foo" />
<button class="hidden peer-[:not(:placeholder-shown):focus]:block">
CloseCrossIcon
</button>
</label>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论