gpt4 book ai didi

javascript - 如何用JS显示 block 和无所有背景图像以绝对方式堆叠?

转载 作者:行者123 更新时间:2023-12-02 22:47:24 24 4
gpt4 key购买 nike

我正在加载时动态创建一个包含 16 个 div 的数组。我已经用 CSS 堆叠了所有具有绝对位置的 div。现在,我想以设定的时间间隔显示 block 并不显示任何内容,如果开始和结束达到循环,则一遍又一遍地重复此操作。

这是我的代码:

if (window.innerWidth < 767) {
images.forEach((image, index) => {
let imageDiv = document.createElement('div');
imageDiv.className = `bg-image bg-image-bg${image}`;
hero.appendChild(imageDiv);
console.log(index);
console.log(imageDiv);
});
}

它生成 16 个带有 bg-image 类的 div。现在,我想显示 block 并不显示从 1 到 16 的内容,一遍又一遍地循环。

这就是我想要实现的目标:https://codepen.io/thomasvaeth/pen/JrjyjW (但没有悬停效果)。

我该怎么做?

谢谢。

最佳答案

在创建 img div 时,您将它们插入一个数组中,然后每 500 毫秒调用相同的函数(在我的例子中),它会隐藏所有 img 并逐渐显示正确的:

let imgArr = [];
if (window.innerWidth < 767) {
images.forEach((image, index) => {
let imageDiv = document.createElement('div');
imageDiv.className = `bg-image bg-image-bg${image}`;
hero.appendChild(imageDiv);
console.log(index);
console.log(imageDiv);
imgArr.push(imageDiv);
});
}

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

setTimeout(() => roll(), 0);

或:

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

setInterval(() => roll(), 500);

编辑(询问)

How would i stop function roll if screen is greater then 1200 ?

因此在这种情况下您应该使用 setInterval() 函数:

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

let interv = setInterval(() => roll(), 500);

window.onresize = () => {
let windowWidth = window.innerWidth||d.documentElement.clientWidth||d.getElementsByTagName('body')[0].clientWidth;
clearInterval(interv);
if(windowWidth < 1200) {
interv = setInterval(() => roll(), 500);
} else {
clearInterval(interv);
}
}

关于javascript - 如何用JS显示 block 和无所有背景图像以绝对方式堆叠?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58338526/

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