2 回答
TA贡献1777条经验 获得超3个赞
您可以通过乘以延迟来解决此问题,例如i:setTimeout
for (let i = 0; i < 50; i++) {
setTimeout(function() {
container.style.background = `rgb(${i} , ${i}, ${i})`
}, 1000 * i); // <----- like this
}
演示:
let container = document.querySelector(".container")
for (let i = 0; i < 255; i++) {
setTimeout(function() {
//var randomColor = Math.floor(Math.random() * 12777215).toString(16);
container.style.background = `rgb(${i} , ${i}, ${i})`
}, 1000 * i);
}
<div class="container" style="width:100px;height:100px"></div>
演示(从黑色到白色):
let container = document.querySelector(".container")
let container2 = document.querySelector(".container2")
for (let i = 0; i < 256; i++) {
setTimeout(function() {
container.style.background = `rgb(${i} , ${i}, ${i})`
container2.textContent = `rgb(${i} , ${i}, ${i})`
}, 50 * i);
}
<div class="container" style="width:200px;height:100px"></div>
<div class="container2" style="width:200px;height:100px"></div>
TA贡献1824条经验 获得超5个赞
setTimeout 是异步的
<script type="text/javascript">
let container = document.querySelector(".container")
let i = 0;
function nextTimeout(){
setTimeout(function() {
container.style.background = `rgb(${i} , ${i}, ${i})`;
i++;
if(i<50){
console.log('next');
nextTimeout()
}
},
1000);
}
nextTimeout();
</script>
添加回答
举报