移动端点击链接时如何禁用Group Hover状态残留
解决触屏设备中Tailwind自定义Group Hover背景残留问题
我用以下代码实现了带自定义group hover效果的链接,在支持hover的设备上表现正常,但触屏设备点击链接后,背景覆盖div会持续显示,直到点击屏幕其他位置。尝试过用active、visited状态隐藏透明度,均未生效。
<div class="group relative md:max-w-md"> <a href=""> <div class="absolute -inset-y-2 -inset-x-4 z-0 rounded-3xl bg-gray-200/50 opacity-0 transition group-hover:opacity-100 dark:bg-gray-700/50"></div> <div class="z-10 flex flex-col space-y-1 group-hover:relative"> <p class="text-justify tracking-normal">This is the link</p> <div class="text-accent flex items-center text-sm font-medium"> Know more <svg viewBox="0 0 16 16" fill="none" class="mt-0.5 ml-1 h-4 w-4 stroke-current"> <path d="M6.75 5.75 9.25 8l-2.5 2.25" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path> </svg> </div> </div> </a> </div>
解决方法
触屏设备的点击会触发元素的hover状态并持续保留,单纯用CSS的active/visited无法解决,可通过以下两种方式处理:
方法一:利用Tailwind的:focus-within状态调整
给背景div添加group:focus-within:opacity-0类,当链接获得焦点(触屏点击后)自动隐藏背景:
<div class="group relative md:max-w-md"> <a href=""> <div class="absolute -inset-y-2 -inset-x-4 z-0 rounded-3xl bg-gray-200/50 opacity-0 transition group-hover:opacity-100 group:focus-within:opacity-0 dark:bg-gray-700/50"></div> <div class="z-10 flex flex-col space-y-1 group-hover:relative"> <p class="text-justify tracking-normal">This is the link</p> <div class="text-accent flex items-center text-sm font-medium"> Know more <svg viewBox="0 0 16 16" fill="none" class="mt-0.5 ml-1 h-4 w-4 stroke-current"> <path d="M6.75 5.75 9.25 8l-2.5 2.25" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path> </svg> </div> </div> </a> </div>
方法二:JavaScript监听触摸事件(更精准控制)
给外层group添加触摸事件监听,在触摸开始时触发hover状态,触摸结束后移除,避免状态残留:
<div class="group relative md:max-w-md" id="hoverGroup"> <a href=""> <div class="absolute -inset-y-2 -inset-x-4 z-0 rounded-3xl bg-gray-200/50 opacity-0 transition group-hover:opacity-100 dark:bg-gray-700/50"></div> <div class="z-10 flex flex-col space-y-1 group-hover:relative"> <p class="text-justify tracking-normal">This is the link</p> <div class="text-accent flex items-center text-sm font-medium"> Know more <svg viewBox="0 0 16 16" fill="none" class="mt-0.5 ml-1 h-4 w-4 stroke-current"> <path d="M6.75 5.75 9.25 8l-2.5 2.25" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path> </svg> </div> </div> </a> </div> <script> const hoverGroup = document.getElementById('hoverGroup'); hoverGroup.addEventListener('touchstart', () => { hoverGroup.classList.add('group-hover'); }, { passive: true }); hoverGroup.addEventListener('touchend', () => { setTimeout(() => { hoverGroup.classList.remove('group-hover'); }, 100); }, { passive: true }); </script>
说明
方法一适合快速解决,利用CSS原生状态自动处理;方法二更灵活,适合需要自定义触摸行为的场景。两种方法都能保留桌面端的hover体验,同时解决触屏设备的状态残留问题。
内容的提问来源于stack exchange,提问作者Shashi Kiran
相关产品推荐
相关产品推荐

