简体   繁体   English

使用JQuery绑定“窗口”的“焦点”和“模糊”功能,在IE中不起作用

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

I need to use JQuery like the follwoing: 我需要像下面这样使用JQuery:

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

jQuery(window).bind("blur", function(event)
{
focusFlag = 0;
});

Does anyone know why this doesn't work for IE? 有谁知道为什么这对IE不起作用?

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. 请注意,在FF和IE中,“Focus”事件会在〜文档加载时触发,而在Chrome中,只有在窗口失去焦点之前才会触发,现在它已经重新获得了焦点。

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. 我只是重复Shedal和roosteronacid所说的,你需要先将DOM准备好才能将事件绑定到它上面,否则在某些浏览器中计算机会说不,它会无声地死掉。

To do this you use the jQuery .ready() function explained by roosteronacid: 为此,您可以使用roosteronacid解释的jQuery .ready()函数:

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. 它的作用是.ready()函数只会在DOM从服务器完全加载时触发并运行其中的代码。

The only real changes I have made is that I hug my brackets for easy reading but it's a personal preference. 我所做的唯一真正的改变是我拥抱我的括号以便于阅读,但这是个人偏好。

$(window)

does not work in all browsers. 不适用于所有浏览器。

Try 尝试

$('body') 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM