在Chrome的Ominbox上按下输入键时触发键盘事件监听器 [英] Keyup event listener fires when enter is pressed on Chrome's Ominbox

查看:424
本文介绍了在Chrome的Ominbox上按下输入键时触发键盘事件监听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在chrome浏览器中,当使用这段代码时:

  $(document).on('keyup',function() {
alert(嘿);
});

每次按下在url中输入栏(例如,当我剪切并粘贴页面本身的URL时)事件监听器触发。
为什么会发生这种情况?



编辑:

因为url栏不在文档(也许在窗口?)中,并且firefox没有这种行为。当我查找 e.target 时,Chrome Inspector显示 body



我认为这可能是由事件冒泡引起的,所以我尝试了这一点:

  $(document).on(' (e){
e.stopPropagation();
alert(嘿);
});

但它不起作用。
我怎样才能防止它被触发?

解决方案

发生这种情况是因为一旦您在多功能框中按下Enter键,焦点转向页面。如果您对 onkeydown 尝试了同样的事情,则多功能框将不会改变任何内容,因为如您所说,它不是文档的一部分。过滤多功能框错误事件的一种方法是检查每个 keyup 是否有一对keydown。

 <脚本> 
var down = false;
document.addEventListener('keydown',function(){
down = true;
},false);

document.addEventListener('keyup',function(){
if(down === true){
alert('它来自页面!');
}
else {
alert('Omnibox。Ignore it。');
}
down = false;
},false);

< / script>

Demo。



制作自己的HTML页面并尝试使用它,因为PasteHTML.com会将其填充到iframe中。为使它在那里正常工作,请首先点击文本以提供iframe焦点。



演示。
请记住使用鼠标专注于多功能框和类型,而不是键盘快捷键。 (引发onkeydown事件,造成误判)



更新:从Chrome 35开始,这种情况不再发生。不过,我不知道他们修复了哪个版本。


In chrome browser, when using this snippet:

  $(document).on('keyup', function(){
    alert("Hey");
  });

Every time I press enter in the url bar (for example when I cut and paste the url of the page itself) the event listener fires. Why does it happen?

EDIT:

It surprised me because url bar is not in document (maybe in window?) and firefox does not have this behaviour. When I look for e.target, Chrome Inspector shows body.

I thought this could be caused by event bubbling so I tried this:

  $(document).on('keyup', function(e){
    e.stopPropagation();
    alert("Hey");
  });

But it doesn't work. How can I prevent it from being triggered?

解决方案

This happens because once you hit enter in the omnibox, the focus turns to the page. If you tried the same thing with onkeydown, the omnibox would change nothing, because as you said, it isn't a part of the document. One way to filter the omnibox's false event out would be to check that every keyup has a pair keydown.

<script>
var down = false;
document.addEventListener('keydown', function (){
    down = true;
}, false);

document.addEventListener('keyup', function (){
    if(down === true){
        alert('It was from the page!');
    }
    else{
        alert('Omnibox. Ignore it.');
    }
    down = false;
}, false);

</script>

Demo.

Make your own HTML page and try it preferably, because PasteHTML.com stuffs it into an iframe. For it to work correctly there, click on the text first to give the iframe focus.

Demo. Remember to use your mouse to focus on the omnibox and type, not a keyboard shortcut. (That fires the onkeydown event, creating a false positive)

Update: As of Chrome 35, this doesn't happen anymore. I don't know which version they fixed it on, however.

这篇关于在Chrome的Ominbox上按下输入键时触发键盘事件监听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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