为什么选项卡按键导致焦点更改也会触发键盘事件? [英] Why is tab keypress causing focus change also triggering keyup event?

查看:118
本文介绍了为什么选项卡按键导致焦点更改也会触发键盘事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  a :< input type ='text'/>< br /> 
b:< input type ='text'onkeyup ='alert(wtf?)'/>< br />

http://jsfiddle.net/59SnP/



由于我的控件也使用标签(不在示例中)我想要焦点关注的keyup事件被消耗(但是我想要接收其他非焦点更改相关的选项卡事件)。我试图研究当前行为背后的理由,但一无所知。问题:指定此当前行为(焦点更改不消耗的事件)以及强制使用它的跨浏览器解决方法。 Thx。

解决方案

您可以尝试这个。我在您的输入中更改了keyup事件:

 < input type ='text'onkeyup =if(!tabPressed){ alert('这是它!');}/> 

我添加了一个小事件处理程序,当选项卡按钮:

  var tabPressed = false; 
document.addEventListener('keydown',function(e){
if(e.keyCode == 9){
tabPressed = true;
} else {
tabPressed = false;
}
},false);


Pressing the tab key which triggers a focus change is also received by the input receiving the focus as a keyup.

a: <input type='text'/><br/>
b: <input type='text' onkeyup='alert("wtf?")'/><br/>

http://jsfiddle.net/59SnP/

As my control also uses tab (not in the example), I would want the focus related keyup event being consumed (but I want to receive other non-focus-change related tab events). I tried to research the rationale behind the current behavior but found nothing. The question: Where is this current behavior specified (event not consumed by focus change), and what would be a cross-browser workaround to force consuming it. Thx.

解决方案

You can try this. I changed your keyup event in your input :

<input type='text' onkeyup="if(!tabPressed){ alert('This is it !'); }"/>

And I added a little event handler which will raise a flag when the tab button is pressed :

var tabPressed = false;
document.addEventListener('keydown', function (e) {
    if(e.keyCode == 9) {
        tabPressed = true;   
    } else {
        tabPressed = false;
    }
}, false);

这篇关于为什么选项卡按键导致焦点更改也会触发键盘事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆