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

前端 未结 2 794
北恋
北恋 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: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('
    Focused ' + times + ' times'); }).on( "blur", function(){ prevActiveElement = null; });​

提交回复
热议问题