javascript - 为什么当浏览器选项卡不在焦点时我的脚本会中断
问题描述
当页面加载时,背景条纹的脚本运行良好。条纹出现,然后在阵列中有一定数量的条纹后开始淡出。
只要选择(聚焦)浏览器选项卡,脚本就会按预期运行。但是,如果您打开新浏览器选项卡并选择新选项卡。条纹的脚本继续在原始选项卡的后台运行,但不知何故忽略了条件,条纹堆积到无穷大。切换回原始选项卡时,您会看到丑陋的堆积。
为什么会这样?
https://codepen.io/trentHarlem/full/yLVvvav
const addButton = document.getElementById('add-stripe');
const guitar = document.getElementById('guitar');
function addStripe() {
let qsaSpan = document.querySelectorAll('span');
let stripe = document.createElement('span');
let stripeArray = Array.from(qsaSpan);
let color = 'white';
let z = Math.floor(Math.random() * 2);
if (Math.random() > 0.65) {
color = 'black';
}
let angle = Math.floor(Math.random() * 360);
let x = Math.floor(Math.random() * 30) - 15;
let y = Math.floor(Math.random() * 30) - 15;
let width = Math.floor(Math.random() * 6) + 1;
// console.log('click', color, angle, x, y, width);
stripe.style.backgroundColor = `${color}`;
stripe.style.zIndex = `${z}`;
stripe.style.transform += `translateX(${x}%)`;
stripe.style.transform += `translateY(${y}%)`;
stripe.style.transform += `rotate(${angle}deg)`;
stripe.style.height = `${width}%`;
guitar.insertAdjacentElement('beforeend', stripe);
// console.log('length', stripeArray.length);
function parRemove() {
stripeArray[0].remove()
stripeArray[0].removeEventListener('transitionend', parRemove)
stripeArray[0].removeEventListener('webkitTransitionEnd', parRemove)
}
if (stripeArray.length > 5) {
stripeArray[0].classList.add('fall');
stripeArray[0].classList.add('fade');
// console.log(' stripeArray[0].classList', stripeArray[0].classList.value);
stripeArray[0].addEventListener('transitionend', parRemove, false);
stripeArray[0].addEventListener('webkitTransitionEnd', parRemove, false);
}
else if (stripeArray.length < 5) {
}
}
const stripeTimer = setInterval(addStripe, 2000);
解决方案
推荐阅读
- bash - 使用 bash 脚本时如何从用户输入创建目录
- python - 如何将具有许多注释行的数据文本文件加载到熊猫中?
- c# - 使用数据注释在 c# 中进行数据验证
- linux - 脚本通知节点关闭
- reactjs - Material UI 图标中的标签
- html - 从经合组织刮一张表
- python - WSGI 应用程序“mysite.wsgi.application”无法加载;导入模块出错
- android - Flutter : Provider 不更新前一屏的数据
- arrays - 计算 array_agg 中的值
- python - 即使更改代码后,AWS Lambda python 函数输出仍然是“来自 Lambda 的你好”