gpt4 book ai didi

javascript - 改变 block 的颜色

转载 作者:太空宇宙 更新时间:2023-11-04 02:30:33 25 4
gpt4 key购买 nike

有 4 个 block 。我需要让他们每个人依次将背景颜色更改为红色。在第二圈我得到一个错误。如何修复?

var spanElems = [].slice.call( document.querySelectorAll('.block__item') ),
i = 0, timer, prev;

(function foo() {
spanElems[prev || 0].style.background = '';

prev = i;
spanElems[i++ % spanElems.length].style.background = 'red';
console.log(i, prev);
timer = setTimeout(foo, 3000);
})();
.block {
margin-top: 100px;
}

.block__item {
padding: 10px;
border: 2px solid #ccc;
}
<div class="block">
<span class="block__item">1</span>
<span class="block__item">2</span>
<span class="block__item">3</span>
<span class="block__item">4</span>
</div>

沙盒:http://jsbin.com/lowimewegu/edit?html,output

最佳答案

问题是 prev 最终大于 spanElems.length,所以 spanElems[prev] 是未定义的。尝试:prev = i % spanElems.length; 代替 prev = i;

关于javascript - 改变 block 的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36585970/

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