Using JQuery to bind “focus” and “blur” functions for “window”, doesn't work in IE

前端 未结 3 1244
遥遥无期
遥遥无期 2020-11-29 04:47

I need to use JQuery like the follwoing:

var focusFlag = 1;
jQuery(window).bind(\"focus\", function(event)
{
focusFlag = 1;
});

jQuery(window).bind(\"blur\"         


        
相关标签:
3条回答
  • 2020-11-29 05:25

    Just to have the right answer here:

    $(function() {
        $(window).focus(function() {
            console.log('Focus');
        });
    
        $(window).blur(function() {
            console.log('Blur');
        });
    });
    

    Note that in FF and IE the "Focus" event fires on ~document load, while in Chrome it only fires if the window had lost focus before and now it has regained it.

    0 讨论(0)
  • 2020-11-29 05:43
    $(window)
    

    does not work in all browsers.

    Try

    $('body') 
    
    0 讨论(0)
  • 2020-11-29 05:47

    I'm only repeating what Shedal and roosteronacid have said, you need the DOM to be ready before you can bind events to it otherwise in some browsers computer will say no and it will die silently.

    To do this you use the jQuery .ready() function explained by roosteronacid:

    var focusFlag = 1;
    
    jQuery(document).ready(function(){
        jQuery(window).bind("focus",function(event){
            focusFlag = 1;
        }).bind("blur", function(event){
            focusFlag = 0;
        });
    });
    

    What it does is the .ready() function will only fire and run the code inside it when the DOM has completely loaded from the server.

    The only real changes I have made is that I hug my brackets for easy reading but it's a personal preference.

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