【问题标题】:jQuery( document ).ready() + wait for focusjQuery( document ).ready() + 等待焦点
【发布时间】:2017-10-19 09:41:02
【问题描述】:

伙计们,

有人刷新了他们的所有标签。我的标签位于非活动的非前景标签中。

运行:jQuery(document).ready().

所以:

  • 如何让动画仅在选项卡变为活动状态时运行?

  • 如果选项卡处于前台并且仍然处于活动状态,我如何让它运行?

我试过了:

<script>jQuery( document ).ready(function() { jQuery(window).focus(function () { setTimeout(function(){ jQuery('.juiz-outdated-message').addClass('active'); }, 500); }); });</script>

这种情况发生在很多网站上,但我找不到任何关于如何做到这一点的资源?!

【问题讨论】:

  • @gurvinder372,感谢您的评论,但正如您从我的问题中的代码片段中看到的那样,我已经尝试过了,但它不起作用。

标签: javascript jquery animation focus


【解决方案1】:

如果选项卡处于前台并且仍然处于活动状态,我如何让它运行?

使用page visibility api,您需要处理visibilitychange事件

如何让我的动画仅在选项卡变为活动状态时运行?

这是来自共享文档链接的示例代码。

function handleVisibilityChange() {
  if (document.hidden) {
    pauseSimulation();
  } else  {
    startSimulation();
  }
}

document.addEventListener("visibilitychange", handleVisibilityChange, false);

共享文档链接还针对不同的浏览器提供了其他回退,同样已在here 进行了详细讨论。

【讨论】:

  • 我明白了,谢谢。所以没有'firstfocus'或类似的事件。我只需要首先检查它是否有焦点。谢谢!
【解决方案2】:

使用@gurvinder372 提供的逻辑回答我自己的问题:

function animateeeee() { //the magic function
	setTimeout(function(){ jQuery('.juiz-outdated-message').addClass('active'); }, 500);
}; 
jQuery( document ).ready(function() { //runs on DOM ready
    if (document.hasFocus()) { //if we already have focus...
	    animateeeee(); //do it now
     } else { //otherwise
		jQuery(window).focus(function() { //bind to focus
			animateeeee();// then run
		});		     
     }; 
 });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-03
    • 2010-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-19
    • 1970-01-01
    • 2014-04-20
    相关资源
    最近更新 更多