[英]Custom button remove focus on click but not on Enter keypress
Whats the best approach to remove focus from a button on mouse click but not when the Enter
key is pressed using Javascript? 什么是从鼠标单击按钮上移开焦点而不是使用Javascript按下Enter
键时移开焦点的最佳方法? I am using the blur()
method on the click
event but that doesn't work. 我在click
事件上使用blur()
方法,但是不起作用。
Please note that I cannot use outline: none
or outline: 0
for accessibility reasons. 请注意,由于可访问性原因,我不能使用outline: none
或outline: 0
。 For more info refer to: http://www.outlinenone.com/ 有关更多信息,请参阅: 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 solution 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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.