这是一个简单的解决方案,使用纯 Javascript,可以追溯到 IE 10。
这个答案类似于@kuba 的答案。使用 JS 添加/删除类以检测鼠标单击或选项卡按钮按下。
javascript:
var htmlElement = document.querySelector('html');
document.addEventListener('click', function(){
htmlElement.classList.add('clicking');
});
document.addEventListener('keyup', function(e){
if (e.keyCode === 9) {
htmlElement.classList.remove('clicking');
}
});
然后在点击类存在时关闭 :focus 上的轮廓
CSS:
html.clicking .targetElement:focus {
outline: none;
}
/*
or you can try dealing with all visibly focusable elements from the start. I'm not sure if this is all of them, but it's good starting point.
*/
html.clicking a:focus,
html.clicking button:focus,
html.clicking input:focus,
html.clicking textarea:focus {
outline: none;
}
浏览器兼容性:
querySelector IE 8+
element.classList IE 10+
如果您需要支持早于 IE10 的浏览器,可以使用 jQuery。
$(document).on('click', function(){
$('html').addClass('clicking');
});
$(document).on('keyup', function(){
if (e.keyCode === 9) {
$('html').removeClass('clicking');
}
});