最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is there any alternative to jQuerys "blur" and "focus" functions? - Stack Overf

programmeradmin1浏览0评论

I have an counter on my site and I want this to pause when my site isnt focused. If I use the blur (someone leaves the focus) and someone clicks on a link that opens in a new tab and then closes the tab the focus isn't back on the previous page? Why doesnt it work? Is there a better way to do it?

$(document).blur(function(){
    pause=true;
});

$(document).focus(function(){
    //alert("test");
    pause=false;

    countdown(tmp,msg);
});

I have an counter on my site and I want this to pause when my site isnt focused. If I use the blur (someone leaves the focus) and someone clicks on a link that opens in a new tab and then closes the tab the focus isn't back on the previous page? Why doesnt it work? Is there a better way to do it?

$(document).blur(function(){
    pause=true;
});

$(document).focus(function(){
    //alert("test");
    pause=false;

    countdown(tmp,msg);
});
Share Improve this question edited Nov 9, 2015 at 12:32 Anders 8,65310 gold badges60 silver badges99 bronze badges asked May 14, 2012 at 10:06 heiningairheiningair 4511 gold badge6 silver badges23 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

I think it's not attached to document, but on window

$(window).focus(function(){...});
$(window).blur(function(){...});

The ones that I always encounter are the native JS versions window.onfocus and window.onblur. I suppose these are also used/abstracted in jQuery as well.

Essentially you don't gain focus until someone clicks or tabs into the page, that's just how focus works. Working code below :-

 $(function() {

    $(window).focus(function() {
        alert("in");
    });
     $(window).blur(function() {
        alert("out");
    });

});

You could add window mouse in/out events however I wouldn't remend this as touch devices won't be supported and people using multiple screens will have issues.

Your problem is more of a software one rather than a JS issue. In this case you are at the mercy of the browser, although you go back to the tab you want you are still in blur state until you click in the window itself.

Can manage with 'click' and outside click with below code

$(document).click(function() {
    //hide
});
$(document).keyup(function(e) {
    //manage tab event 
    if (e.target.id == "idName") {
        //show
    } else {
        //hide
    }
});

$(#idName).bind('click', function(e) {
    //show 
    e.stopPropagation();
});
发布评论

评论列表(0)

  1. 暂无评论