gpt4 book ai didi

javascript - 自定义按钮移除单击时的焦点,但不移除 Enter 按键的焦点

转载 作者:行者123 更新时间:2023-12-02 14:08:32 24 4
gpt4 key购买 nike

在鼠标单击时从按钮上移除焦点但在使用 Javascript 按下 Enter 键时不移除焦点的最佳方法是什么?我在 click 事件上使用 blur() 方法,但这不起作用。

请注意,出于可访问性原因,我无法使用 outline: noneoutline: 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com