使用函数慢慢增加背景颜色的数量

我正在尝试使用以下代码慢慢增加背景的颜色:


<script type="text/javascript">

        let container = document.querySelector(".container")

        for(let i = 0 ; i<50; i++) {

            setTimeout(function() {

                container.style.background = `rgb(${i} , ${i}, ${i})`},

                1000);

            }

</script>

我不确定为什么它不起作用。当我使用 console.log(i) 时,它似乎没有正确迭代。我希望它在每次迭代时暂停。我该怎么做呢?


GCT1015
浏览 86回答 2
2回答

慕森王

您可以通过乘以延迟来解决此问题,例如i:setTimeoutfor (let i = 0; i < 50; i++) {&nbsp; &nbsp;setTimeout(function() {&nbsp; &nbsp; &nbsp; container.style.background = `rgb(${i} , ${i}, ${i})`&nbsp; &nbsp;}, 1000 * i);&nbsp; // <----- like this}演示:let container = document.querySelector(".container")for (let i = 0; i < 255; i++) {&nbsp; setTimeout(function() {&nbsp; &nbsp; //var randomColor = Math.floor(Math.random() * 12777215).toString(16);&nbsp; &nbsp; container.style.background = `rgb(${i} , ${i}, ${i})`&nbsp; &nbsp;&nbsp;&nbsp; }, 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++) {&nbsp; setTimeout(function() {&nbsp; &nbsp; container.style.background = `rgb(${i} , ${i}, ${i})`&nbsp; &nbsp; container2.textContent = `rgb(${i} , ${i}, ${i})`&nbsp; }, 50 * i);}<div class="container" style="width:200px;height:100px"></div><div class="container2" style="width:200px;height:100px"></div>

沧海一幻觉

setTimeout 是异步的<script type="text/javascript">&nbsp; &nbsp; let container = document.querySelector(".container")&nbsp; &nbsp; let i = 0;&nbsp; &nbsp; function nextTimeout(){&nbsp; &nbsp; &nbsp; setTimeout(function() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; container.style.background = `rgb(${i} , ${i}, ${i})`;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; i++;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(i<50){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log('next');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; nextTimeout()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; 1000);&nbsp; &nbsp; }&nbsp; &nbsp; nextTimeout();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;</script>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript