gpt4 book ai didi

javascript - 如果屏幕宽度大于 1200px,禁用 setTimeout 函数?

转载 作者:行者123 更新时间:2023-11-28 03:28:58 25 4
gpt4 key购买 nike

我有 16 个动态创建的带有背景图像的 div。我有一个功能,可以向每个背景图像添加样式,不显示任何内容并阻止我一遍又一遍地循环。

当前,如果屏幕宽度小于 1200px,并且仅在重新加载/初始化时有效。

我现在面临的最大问题是,当初始化时屏幕宽度大于 1200px 并且我将大小调整回 1000px 时,动画将无法启动。

我想要实现的是,当我调整大小并超过 1200px 时,显示 block /无将在窗口大小:< 1200px 上工作,并且如果屏幕 > 1200px 则停止工作。

工作演示:https://codepen.io/Merdzanovich/pen/abbvPGv

有人可以帮忙吗?

代码:

(() => {
const hero = document.getElementById('hero');

if (!hero) {
return;
}

const shuffle = array => {
let currentIndex = array.length;
let temporaryValue, randomIndex;

while (0 !== currentIndex) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;

// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}

return array;
};

const images = Array.from(Array(16).keys(), n => n + 1);
const shuffleArray = shuffle(images);
let imgArr = [];
let counter = 0;

function roll() {
imgArr.map(img => (img.style.display = 'none'));
imgArr[counter].style.display = 'block';
counter++;
if (counter === imgArr.length - 1) {
counter = 0;
}

setTimeout(() => roll(), 500);
}

const init = () => {
shuffleArray.forEach(image => {
let imageDiv = document.createElement('div');
imageDiv.className = `bg-image bg-image-bg${image}`;
hero.appendChild(imageDiv);
imgArr.push(imageDiv);
});

if (window.innerWidth < 1200) {
setTimeout(() => roll(), 0);
}
};

window.addEventListener('load', init);
})();

最佳答案

您需要使用clearTimeout

将设置的超时保存到变量中,以便您可以在clearTimeout() 调用中引用它

var myVar;

function myFunction() {
myVar = setTimeout(function(){ alert("Hello"); }, 3000);
}

function myStopFunction() {
clearTimeout(myVar);
}

编辑:也许 setInterval 在这里更合适,因为您需要不断检查窗口大小:

setInterval(function() { 
if (window.innerWidth < 1200) {
// do the thing you want if its smaller than 1200
} else {
// do the other thing
}
}, 3000);

关于javascript - 如果屏幕宽度大于 1200px,禁用 setTimeout 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58342062/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com