Changing browser tabs undesirably fires the focus event, especially in Google Chrome

前端 未结 2 793
北恋
北恋 2021-02-19 04:37

I\'ve got a little issue with the focus event that I just became aware of. Apparently, focus fires when switching to another browser tab and then back again. I\'d rather not hav

相关标签:
2条回答
  • 2021-02-19 05:00

    Try this to get around the problem:

    var times = 0, foc=true;
    
    $(window).on('focus', function() {
        foc = false;
        setTimeout(function() {foc=true}, 200);
    });
    
    $('input').on('focus', function() {
        if (foc || times===0) {
            times ++;
            $(this).after('<br>Focused '+times+' times');   
        }
    });
    

    FIDDLE ​

    0 讨论(0)
  • 2021-02-19 05:02

    Try this

    var times = 0;
    var prevActiveElement;
    
        $( window ).on( "blur", function(e){
                prevActiveElement = document.activeElement;
        });
    
        $('input').on('focus', function() {
            if (document.activeElement === prevActiveElement) {
                return;
            }
            prevActiveElement = document.activeElement;
            times++;
            $(this).after('<br>Focused ' + times + ' times');
        }).on( "blur", function(){
            prevActiveElement = null;  
        });​
    
    0 讨论(0)
提交回复
热议问题