如何强制浏览器重检元素:active状态?解决Chrome状态残留问题
Chrome中:active状态卡顿问题的解决办法
示例代码
CSS
div:active { color: red; }
HTML
<div>test</div>
问题描述
在上述示例中,Chrome内的元素可能卡在:active状态——即便鼠标离开元素,Chrome仍会对其应用:active样式。
桌面端Chrome中,页面产生新交互后:active样式会自动消失;但Android端Chrome里,该样式会持续保留到页面刷新。这个问题常出现在点击带:active样式的元素后立即切换应用的场景,推测是切换回Chrome时,浏览器未检查元素是否已脱离:active状态。
需求
希望找到方法强制浏览器重新检查所有元素的:active状态,且能在切换回Web应用时(通过visibilitychange事件)触发该操作。
已尝试的无效方法
添加/移除display: none、调用document.activeElement.blur()、让其他元素focus()、添加tabindex等,仅移除并重新添加样式有效,但该方式易出错。
可行解决方案
方案1:派发全局mouseup事件
利用visibilitychange事件,当页面重新可见时派发全局mouseup事件,触发浏览器重置:active状态(因为:active通常在鼠标松开时结束):
document.addEventListener('visibilitychange', () => { if (!document.hidden) { document.dispatchEvent(new MouseEvent('mouseup', { bubbles: true, cancelable: true, view: window })); } });
方案2:用自定义类替代原生:active伪类
通过JavaScript手动控制自定义类的添加与移除,完全掌控状态,避免浏览器原生伪类的卡顿问题:
修改后的CSS
div.active { color: red; }
控制逻辑
const targetDiv = document.querySelector('div'); // 绑定交互事件控制类 targetDiv.addEventListener('mousedown', () => targetDiv.classList.add('active')); targetDiv.addEventListener('mouseup', () => targetDiv.classList.remove('active')); targetDiv.addEventListener('mouseleave', () => targetDiv.classList.remove('active')); targetDiv.addEventListener('touchstart', () => targetDiv.classList.add('active')); targetDiv.addEventListener('touchend', () => targetDiv.classList.remove('active')); // 页面重新可见时清除所有active类 document.addEventListener('visibilitychange', () => { if (!document.hidden) { document.querySelectorAll('.active').forEach(el => el.classList.remove('active')); } });
内容的提问来源于stack exchange,提问作者Leo Jiang
相关产品推荐
相关产品推荐

