Different behavior of blur event in different browsers

后端 未结 3 555
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-15 10:14

Consider this example where I have 2 input fields:



And consider t

3条回答
  •  时光说笑
    2020-12-15 10:56

    As you know, the issue is that different browsers choose to call event handlers in different orders. One solution is to give the other events a chance to fire by setting a timer for 0 milliseconds, and then checking the fields to see which (if any) is focused.

    a.onfocus = function() {show(b);};
    
    a.onblur = function() {
        setTimeout(function() {
            //if neither filed is focused
            if(document.activeElement !== b && document.activeElement !== a){
                hide(b);
            }
                }, 0);
    };
    
    //same action as for a
    b.onblur = a.onblur;
    

    Tested in Chrome, Firefox, Internet Explorer, and Safari. See full working example (edited version of your fiddle) at JSFiddle.net.

提交回复
热议问题