窗口失焦时恢复选项

时间:2015-04-18 20:35:03

标签: javascript jquery timer

我正在运行基于窗口焦点的计时器。如果窗口处于焦点,那么计时器将向前移动,否则将显示消息。我在focusmsg div中显示焦点消息,并在窗口处于焦点时隐藏此div。因此,焦点输出消息不可见。

现在,我不想显示简单的焦点消息,而是要显示一个简历按钮,以便用户需要单击“恢复”按钮,以确保在返回到焦点不对称的窗口后窗口处于焦点。< / p>

请记住,在用户通过单击“恢复”按钮确保窗口聚焦之前,恢复按钮不应消失。

如果你能提供一个jsfiddle你的答案,那对我来说会很棒!

    if(w_focus) {
        $("#focusmsg").hide();

        var timer = 0;
        var full = 10;
        timer++;

        if(timer == full) {
            var show = "Full";
            $("#timmsg").html(show);
        }


        else {
            setTimeout(adTimer, 1000);
            $("#between").hide();
        }
    } else {
        setTimeout(adTimer, 2000);

        var msg = "Focus lost! Resume now";
        $("#focusmsg").html(msg);
    }


$(document).ready(function() {

        var hidden, change, vis = {
            hidden: "visibilitychange",
            mozHidden: "mozvisibilitychange",
            webkitHidden: "webkitvisibilitychange",
            msHidden: "msvisibilitychange",
            oHidden: "ovisibilitychange" /* not currently supported */
        };             
    for (hidden in vis) {
        if (vis.hasOwnProperty(hidden) && hidden in document) {
            change = vis[hidden];
            break;
        }
    }
    if (change)
        document.addEventListener(change, onchange);
    else if (/*@cc_on!@*/false) // IE 9 and lower
        document.onfocusin = document.onfocusout = onchange
    else
        window.onfocus = window.onblur = onchange;

    function onchange (evt) {
        evt = evt || window.event;
        if (evt.type == "focus" || evt.type == "focusin")
           window_focus = true;
        else if (evt.type == "blur" || evt.type == "focusout")
           window_focus = false;
        else        
           window_focus = this[hidden] ? false : true;
    }

});

1 个答案:

答案 0 :(得分:1)

单击恢复按钮时,可以使用以下命令将w_focus变量设置为true。请注意,您必须删除window.onfocus函数,而只是使用它,因此当用户实际单击“恢复”按钮时,它只会将w_focus变量设置为true。

直播示例:

&#13;
&#13;
var w_focus = true;

window.onblur = function() {
  w_focus = false;
  $('#resume-button').show();
}

$('#resume-button').on('click', function() {
  w_focus = true;
  $('#resume-button').hide();
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="resume-button" style="display:none">Resume</button>
&#13;
&#13;
&#13;

(尝试运行此代码片段,然后转到另一个选项卡或打开另一个应用程序,然后返回。您应该看到简历按钮,这将消失,并将w_focus变量设置为true点击它)

链接到正常工作的JSFiddle示例: http://jsfiddle.net/3tzmeta4/