空格并输入“点击”在关注的输入上。如何禁用此行为?
在chrome和firefox(以及其他人)中,如果你有一个聚焦的输入,按空格和输入会为你点击它们。我正在制作一个HTML 5游戏,我想重写空间和输入对焦点的反应,默认行为正在妨碍我。有没有办法在大多数浏览器中关闭此默认行为?
In chrome and firefox (and maybe others), if you've got an input focused, pressing "space" and "enter" clicks them for you. I'm making an HTML 5 game and I want to rewrite how space and enter reacts on focus and the default behavior is getting in my way. Is there a way to turn this default behavior off in most browsers?
这是一个jsfiddle ,展示了这个问题。
Here's a jsfiddle demonstrating the problem.
<button>Button<button>
$("button").on("click", function(event) { alert("Clicked"); });
如果单击按钮,它会显示良好的警报。但如果您在单击后按空格或输入,它也会发出警报。我想防止这种行为,这样我就可以在没有干扰的情况下编写自己的行为。
If you click on the button, it displays the alert which is good. But if you press "space" or "enter" after you click it, it also alerts. I want to prevent this behavior so that I can write my own without them interfering.
您可以使用 event.detail
。这将返回单击按钮的次数。如果按Enter键,则返回0,因为您单击了0次,如果您通过鼠标单击它,它将返回您单击按钮的次数。
You can fix this by using event.detail
. That will return the amount of times the button has been clicked. If you press enter, this returns 0, since you clicked it 0 times, and if you click it via your mouse, it returns the amount of times you clicked the button.
要访问 event.detail
,您需要访问原始事件对象。这可以通过jQuery事件对象中的 event.originalEvent
来完成。所以,如果你只是在你的脚本中添加一个if语句:
To access event.detail
, you need to access the original event object. This can be done via event.originalEvent
in the jQuery event object. So, if you just put an if statement in your script:
if (event.originalEvent.detail != 0) {
//your click event code
}
然后它只会运行你实际上是通过鼠标点击按钮。
then it'll only run if you actually click the button via your mouse.
这比检查按钮是否有:焦点
更准确>,因为单击按钮时按钮会自动聚焦,所以这样做会在单击后禁用按钮。
This will be much more accurate than checking if the button has :focus
, since the button automatically gets focused when you click it, so doing that would disable the button after a single click.