You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TailwindCSS:结合peer-focus-within与not(:peer-placeholder-shown)实现清除图标逻辑

解决TailwindCSS输入框清除图标显示逻辑问题

你的问题出在Tailwind变体的语法使用错误,not(:peer-placeholder-shown)不是Tailwind支持的写法,正确的否定变体应该用not-前缀结合目标状态,同时要正确组合两个条件(输入框聚焦 + 占位符隐藏)。

修正后的实现代码

import { useId, ComponentProps } from 'react';
import clsx from 'clsx';
import CloseCrossIcon from './CloseCrossIcon'; // 假设你的图标组件路径

function ExampleInput({
  label,
  className,
  onClear,
  ...props
}: { label: string; onClear: () => void } & ComponentProps<'input'>) {
  const id = useId();

  return (
    <div>
      <label htmlFor={id} className="relative">
        <span>{label}</span>
        <input
          {...props}
          className={clsx('peer truncate text-lg/6', className)}
          type="text"
          id={id}
        />

        <button
          className="absolute bottom-0.5 right-0.5 hidden peer-focus:not-peer-placeholder-shown:block text-spanishGrey"
          type="button"
          onClick={onClear}
        >
          <CloseCrossIcon height="14" width="14" />
        </button>
      </label>
    </div>
  );
}

关键修正点

  1. 正确的Tailwind变体组合:
    使用peer-focus:not-peer-placeholder-shown:block实现逻辑:当输入框(peer)处于聚焦状态,且输入框内容不为空(占位符隐藏)时,将按钮从hidden改为block显示。
    Tailwind的否定变体语法为not-[状态名],而非嵌套的:not()写法。

  2. 定位修正:
    给包裹的label添加relative类,确保绝对定位的清除按钮能相对于输入框容器正确定位,避免位置偏移。

  3. 语义优化:
    将onClear事件绑定到button元素上,而非内部图标,符合HTML可点击元素的语义规范。

可选:自定义工具类简化写法

如果需要复用这个显示逻辑,可以在Tailwind配置的自定义工具类中封装:

@layer utilities {
  .clear-btn-visible {
    @apply hidden peer-focus:not-peer-placeholder-shown:block;
  }
}

之后按钮直接使用className="absolute bottom-0.5 right-0.5 clear-btn-visible text-spanishGrey"即可。

内容的提问来源于stack exchange,提问作者paulbtw

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 04:32:37