Chrome (maybe Safari?) fires “blur” twice on input fields when browser loses focus

前端 未结 7 1985

Here is an interesting jsfiddle.

In Firefox:

  1. Run the fiddle
  2. Click in text input
  3. Click somewhere else. Should say \"1 bl
7条回答
  •  生来不讨喜
    2020-12-28 16:04

    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/

提交回复
热议问题