在鼠标单击时从按钮上移除焦点但在使用 Javascript 按下 Enter
键时不移除焦点的最佳方法是什么?我在 click
事件上使用 blur()
方法,但这不起作用。
请注意,出于可访问性原因,我无法使用 outline: none
或 outline: 0
。欲了解更多信息,请参阅:http://www.outlinenone.com/
var button = document.getElementById("btn");
button.addEventListener("click", removeFocus);
function removeFocus(event) {
event.target.blur();
}
button {
display: inline-block;
border: none;
height: 36px;
line-height:36px;
padding: 0 12px;
background: cyan;
}
<button id="btn">
Hello
</button>
最佳答案
Javascript解决方案
var button = document.getElementById("btn");
button.addEventListener("click", clickEvent);
button.addEventListener("keypress", clickEvent);
function clickEvent(event){
if (event.keyCode == 13) {
event.preventDefault();
} else {
button.blur();
}
}
button {
display: inline-block;
border: none;
height: 36px;
line-height:36px;
padding: 0 12px;
background: cyan;
}
<button id="btn">
Hello
</button>
关于javascript - 自定义按钮移除单击时的焦点,但不移除 Enter 按键的焦点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39841556/