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

前端 未结 7 1986

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/

    0 讨论(0)
  • 2020-12-28 16:08

    I'm on Chrome Version 30.0.1599.101 m on Windows 7 and this issue appears to have been fixed.

    0 讨论(0)
  • 2020-12-28 16:08

    I am experiencing the same and the above posts make sense as to why. In my case I just wanted to know if at least one blur event had occurred. As a result I found that just returning from my blur function solved my issue and prevented the subsequent event from firing.

       function handleEditGroup(id) {
            var groupLabelObject = $('#' + id);
            var originalText = groupLabelObject.text();
    
            groupLabelObject.attr('contenteditable', true)
                .focus().blur(function () {
                    $(this).removeAttr('contenteditable');
                    $(this).text($(this).text().substr(0, 60));
    
                    if ($(this).text() != originalText) {
                        alert("Change Found");
                        return; //<--- Added this Return.
                    }
                });
        }
    
    0 讨论(0)
  • 2020-12-28 16:16

    Skip 2nd blur:

    var secondBlur = false;
    this.onblur = function(){
        if(secondBlur)return;
        secondBlur = true;
        //do whatever
    }
    this.onfocus = function(){
        secondBlur = false;    
        //do whatever
    }
    
    0 讨论(0)
  • 2020-12-28 16:21

    Looks like an oddity of angularjs gives a simpler solution when using ng-blur; the $event object is only defined if you pass it in:

    ng-blur="onBlur($event)"
    

    so (if you aren't using ng-blur on the window) you can check for:

    $scope.onBlur = function( $event ) {
        if (event != undefined) {
           //this is the blur on the element
        }
    }
    
    0 讨论(0)
  • 2020-12-28 16:23

    This is confirmed Chrome bug. See the Chromium Issue Tracker

    The workaround is in the accepted answer.

    0 讨论(0)
提交回复
热议问题