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

前端 未结 2 792
北恋
北恋 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('
    Focused '+times+' times'); } });

    FIDDLE ​

提交回复
热议问题