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

使用TailwindCSS检测触摸设备 无需JS实现持久化hover状态

无JavaScript实现方案(TailwindCSS 3.3.2)

可以通过Tailwind内置的媒体查询变体实现需求,核心逻辑是:触摸设备上让目标元素始终可见,仅在非触摸设备(精准指针设备)上启用hover效果。

修改后的代码

<div className="mr-2 flex opacity-0 transition-opacity duration-300 touch:opacity-100 group-hover/row:opacity-100">
  <Button
    variant="ghost"
    size="sm"
    className="h-5 w-5 min-w-0 p-0 text-green-200 pointer-fine:hover:text-green-600 sm:h-8 sm:w-8"
  >
    <span className="sr-only sm:not-sr-only sm:inline">
      Edit
    </span>
    <span className="sm:sr-only">E</span>
  </Button>
  <Button
    variant="ghost"
    size="sm"
    className="h-5 w-5 min-w-0 p-0 text-red-500 pointer-fine:hover:text-red-700 sm:h-8 sm:w-8"
  >
    <span className="sr-only sm:not-sr-only sm:inline">
      Delete
    </span>
    <span className="sm:sr-only">X</span>
  </Button>
</div>

关键细节说明

  • 容器可见性控制:
    • 保留原有的opacity-0 group-hover/row:opacity-100,确保非触摸设备hover时显示元素
    • 添加touch:opacity-100,让触摸设备上元素始终保持可见(touch是Tailwind内置变体,匹配支持触摸交互的设备)
  • 按钮hover效果控制:
    • 将原有的hover:text-green-600改为pointer-fine:hover:text-green-600,同理修改红色按钮的hover样式
    • pointer-fine是Tailwind内置变体,仅匹配鼠标、触控笔这类精准指针设备,触摸设备不会触发该hover样式

补充兼容方案(可选)

如果需要兼容同时支持触摸和鼠标的设备,可以自定义hover-not-touch变体,先在tailwind.config.js中配置:

/** @type {import('tailwindcss').Config} */
module.exports = {
  // ...其他配置项
  variants: {
    extend: {
      textColor: ['hover', 'hover-not-touch'],
    },
  },
}

之后按钮的hover类可以写成hover:not-touch:text-green-600,不过绝大多数场景下pointer-fine已经足够覆盖需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 23:10:10