我有一个相当simple scenario我试图防止鼠标按下时出现橙色背景:
document.querySelector('label').addEventListener('mousedown', (event) => {
console.log('mouse down')
event.preventDefault();
})
label:active {
background: orange;
}
<label>Press mouse down</label>
不幸的是,event.preventDefault()
没有效果,标签变成橙色。 (在 Chrome、Safari 和 IE11 中测试)
任何人都可以向我解释其背后的原因,或者告诉我如何在不被黑客攻击的情况下以编程方式阻止事件状态?
最佳答案
It seems like an old issue 。如果需要,您可以使用 pointer-events
属性来修复它。另外,support因为同样相当不错(包括 IE11)
label:active {
background: orange;
}
label {
pointer-events: none;
}
<label>Press mouse down</label>
确保您在 label
元素上声明了一些 class
或 id
,这样您就不会定位所有这些。
JavaScript 解决方案 - 只是尝试一下
这个想法是在 mousedown
上添加一个 class
并使用具有 :active
的 CSS class
覆盖它伪 class
,然后删除 mouseup
上的 class
.. 类似
var overrideActive = function() {
var labelElm = document.querySelector('label');
var bodyElm = document.querySelector('body');
function init() {
//on mousedown, add a class and override it with css
labelElm.addEventListener('mousedown', (event) => {
event.target.className = 'disable-active';
});
//onmouseout get rid of the class
bodyElm.addEventListener('mouseup', (event) => {
labelElm.classList.remove('disable-active');
});
}
return {
init: init
}
}();
overrideActive.init();
label:active {
background: orange;
}
.disable-active:active {
background-color: transparent;
}
<label>Press mouse down</label>
关于javascript - 使用 JavaScript 防止标签处于事件状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44009783/