2017-10-19 159 views
1

民間,jQuery(document).ready()+等待焦點

某人刷新了他們的所有選項卡。我的標籤位於非活動的非前景標籤中。

這將運行:jQuery(document).ready().

所以:

  • 如何讓我的動畫運行,只有當標籤被激活?

  • 我如何得到它運行,如果該標籤是前景和活躍呢?

我曾嘗試:

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

這發生在這麼多的網站我無法找到如何做到這一點的任何資源,但?

+0

@ gurvinder372,感謝,但你可以從我的我問題的代碼片段看已經試過了,它不起作用。 – Harry

回答

0

如何讓它運行,如果選項卡是前景和活動無論如何?

使用page visibility api,你需要處理visibilitychange事件

如何讓我的動畫只在標籤變爲活動狀態時運行?

以下是共享文檔鏈接的示例代碼。

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

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

共享文檔鏈接具有給定的,以及對不同的瀏覽器的其他回退,並且相同的已被詳細討論here

+0

我明白了,謝謝。所以沒有「第一焦點」或類似的事件。我只需要檢查一下它是否有重點。謝謝! – Harry

0

使用什麼樣的邏輯回答我的問題@ gurvinder372友情提供:您的評論

function animateeeee() { //the magic function 
 
\t 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... 
 
\t  animateeeee(); //do it now 
 
    } else { //otherwise 
 
\t \t jQuery(window).focus(function() { //bind to focus 
 
\t \t \t animateeeee();// then run 
 
\t \t }); \t \t  
 
    }; 
 
});

相關問題