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

TailwindCSS中基于按钮焦点切换下拉菜单<a>元素pointer-events属性

解决TailwindCSS下拉菜单链接点击问题:基于按钮焦点切换pointer-events

你只需要给每个<a>标签添加peer-focus:pointer-events-auto类,结合默认的pointer-events-none,就能实现按钮获得焦点时取消禁止点击的状态。同时注意移除下拉菜单容器上多余的peer类(触发焦点的peer是前面的按钮,容器不需要这个类)。

修改后的完整代码:

<script src="https://cdn.tailwindcss.com"></script>

<div
  class="w-full py-12 mt-3 border border-gray-200 dark:border-gray-700 rounded-xl flex flex-col justify-center items-center"
>
  <div class="w-48 flex flex-col text-left">
    <button
      id="basicDropdownButton"
      class="peer flex items-center h-10 px-4 font-semibold rounded-md transition-all shadow-md text-white bg-violet-500 hover:bg-violet-400 dark:hover:bg-violet-600 border border-violet-400"
    >
      Dropdown
      <i class="fa-solid fa-chevron-down text-sm ml-auto"></i>
    </button>
    <div
      id="basicDropdownMenu"
      class="w-full my-1 flex flex-col justify-center items-center rounded-md transition-all bg-gray-50 dark:bg-gray-700 border border-gray-200 dark:border-gray-500 opacity-0 peer-focus:opacity-100"
    >
      <a
        href=""
        class="py-2 w-full pointer-events-none peer-focus:pointer-events-auto text-black/[0.86] dark:text-white font-semibold px-4 hover:bg-gray-200 dark:hover:bg-gray-600"
        >Link 1</a
      >
      <a
        href=""
        class="py-2 w-full pointer-events-none peer-focus:pointer-events-auto text-black/[0.86] dark:text-white font-semibold px-4 hover:bg-gray-200 dark:hover:bg-gray-600"
        >Link 2</a
      >
      <a
        href=""
        class="py-2 w-full pointer-events-none peer-focus:pointer-events-auto text-black/[0.86] dark:text-white font-semibold px-4 hover:bg-gray-200 dark:hover:bg-gray-600"
        >Link 3</a
      >
    </div>
  </div>
</div>

关键修改说明:

  • 按钮保留peer类,作为焦点触发的参照元素
  • 每个<a>标签新增peer-focus:pointer-events-auto,当按钮获得焦点时,这个类会覆盖默认的pointer-events-none,允许链接被点击
  • 移除了下拉菜单容器上的peer类,避免混淆触发逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 15:06:10