这是我写的脚本我想在用户切换到不同的选项卡时停止计时器,并在访问网站时恢复。有人能帮我解决这个任务吗。当浏览器选项卡焦点或在选项卡之间切换时,需要停止计时器倒计时有人帮我查这个代码吗
<div style="text-align: center;">
<a class="button" href="" id="download">Click To Download</a>
<button class="infoblogger" id="btn"> Download</button>
<script>
var downloadButton = document.getElementById("download");
var counter = 45;
var newElement = document.createElement("p");
newElement.innerHTML = "www.xyz.com";
var id;
downloadButton.parentNode.replaceChild(newElement, downloadButton)
function startDownload() {
this.style.display = 'none';
id = setInterval(function() {
counter--;
if (counter < 0) {
newElement.parentNode.replaceChild(downloadButton, newElement);
clearInterval(id);
} else {
newElement.innerHTML = +counter.toString() + " second.Please Wait";
}
}, 1000);
};
var clickbtn = document.getElementById("btn");
clickbtn.onclick = startDownload
</script>
</div>
1st:<script>
标记未在div
元素中使用
2nd:您可以使用一个额外的变量并检查其状态来运行函数
此处使用focusOut
,其值为false,如果窗口最小化或失焦(打开其他选项卡(,则值将变为true,如果重新获得焦点,则值变回false
。此状态用于保持函数运行。
var downloadButton = document.getElementById("download");
var counter = 45;
var newElement = document.createElement("p");
newElement.innerHTML = "www.xyz.com";
var id;
let focusOut = false;
downloadButton.parentNode.replaceChild(newElement, downloadButton)
function startDownload() {
this.style.display = 'none';
id = setInterval(function() {
if (!focusOut) {
counter--;
if (counter < 0) {
newElement.parentNode.replaceChild(downloadButton, newElement);
clearInterval(id);
} else {
newElement.innerHTML = +counter.toString() + " second.Please Wait";
}
}
}, 1000);
};
var clickbtn = document.getElementById("btn");
clickbtn.onclick = startDownload
window.addEventListener('blur', function() {
focusOut = true;
})
window.addEventListener('focus', function() {
focusOut = false;
});
<div style="text-align: center;">
<a class="button" href="" id="download">Click To Download</a>
<button class="infoblogger" id="btn"> Download</button>
</div>
<script>
</script>