Chrome(也许是Safari?)会触发“模糊”浏览器失去焦点时在输入字段上输入两次 [英] Chrome (maybe Safari?) fires "blur" twice on input fields when browser loses focus

查看:188
本文介绍了Chrome(也许是Safari?)会触发“模糊”浏览器失去焦点时在输入字段上输入两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个有趣的jsfiddle。



在Firefox中:


  1. 运行小提琴

  2. 点击文本输入

  3. 点击其他地方。应该说1模糊。

  4. 再次点击文本输入。

  5. ALT-TAB到另一个窗口。小提琴现在应该说2模糊。

在Chrome中,在步骤5中,它显示3模糊。整个浏览器失去焦点时会触发两个单独的模糊事件。这是有趣的,因为这意味着在模糊处理程序中假定该元素在事件被调度之前实际上已经关注是不安全的;那就是失去焦点 - 从关注焦点向不关注焦点过渡 - 是事件的原因。当生成 two blur事件时,在处理第二个事件期间,该条件未得到满足,因为该元素已处于焦点状态。



那这只是一个错误?有没有办法告诉模糊事件是假的?

解决方案

它发射两次的原因是窗口.onblur。作为javascript捕获/冒泡过程的一部分,窗口模糊会触发该窗口中所有元素的模糊事件。所有你需要做的就是测试事件目标作为窗口。

  var blurCount = 0; 
var isTargetWindow = false;
$(window).blur(function(e){
console.log(e.target);
isTargetWindow = true;
});
$(window).focus(function(){
isTargetWindow = false;
});
$('input')。blur(function(e){
if(!isTargetWindow){
$('div')。text(++ blurCount +'blurs');
}
console.log(e.target);
});




http://jsfiddle.net/pDYsM/4/

Here is an interesting jsfiddle.

In Firefox:

  1. Run the fiddle
  2. Click in text input
  3. Click somewhere else. Should say "1 blurs".
  4. Click in the text input again.
  5. ALT-TAB to another window. Fiddle should now say "2 blurs".

In Chrome, at step 5, it says "3 blurs". Two separate "blur" events are fired when the whole browser loses focus. This is of interest because it means that it's not safe to assume, in a "blur" handler, that the element actually had focus just before the event was dispatched; that is, that the loss of focus — the transition from "being in focus" to "not being in focus" — is the reason for the event. When two "blur" events are generated, that condition is not satisfied during the handling of the second event, as the element is already not in focus.

So is this just a bug? Is there a way to tell that a "blur" event is bogus?

解决方案

The reason it is firing twice is because of window.onblur. The window blurring triggers a blur event on all elements in that window as part of the way javascript's capturing/bubbling process. All you need to do is test the event target for being the window.

var blurCount = 0;
var isTargetWindow = false;
$(window).blur(function(e){
    console.log(e.target);
    isTargetWindow = true;
});
$(window).focus(function(){
    isTargetWindow = false;
});
$('input').blur(function(e) {
    if(!isTargetWindow){         
       $('div').text(++blurCount + ' blurs');
    }
    console.log(e.target);
});

http://jsfiddle.net/pDYsM/4/

这篇关于Chrome(也许是Safari?)会触发“模糊”浏览器失去焦点时在输入字段上输入两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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