首页 > 解决方案 > 为什么当浏览器选项卡不在焦点时我的脚本会中断

问题描述

当页面加载时,背景条纹的脚本运行良好。条纹出现,然后在阵列中有一定数量的条纹后开始淡出。

只要选择(聚焦)浏览器选项卡,脚本就会按预期运行。但是,如果您打开新浏览器选项卡并选择新选项卡。条纹的脚本继续在原始选项卡的后台运行,但不知何故忽略了条件,条纹堆积到无穷大。切换回原始选项卡时,您会看到丑陋的堆积。

为什么会这样?

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);


标签: javascriptbrowser

解决方案


推荐阅读