带有循环的jQuery字体颜色动画

我需要一个没有 CSS3 函数的 jQuery 彩色动画。


我编码了这个:


function button_selection() {

    setTimeout(button_selection, 800);

    setTimeout(function () { $(".color").css("color", "yellow"); }, 200);

    setTimeout(function () { $(".color").css("color", "blue"); }, 400);

    setTimeout(function () { $(".color").css("color", "red"); }, 600);

    setTimeout(function () { $(".color").css("color", "green"); }, 800);

}

setTimeout(button_selection, 0);

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<h1 class="color">Hello world, I love you all.</h1>


在我的浏览器中,它可以工作。但我认为代码并不是真的“好”。怎么可能将颜色写在一行中,然后只控制速度?


谢谢。


隔江千里
浏览 102回答 4
4回答

梦里花落0921

你不需要 jQuery。制作一个计数器,每n毫秒递增一次,并根据计数器状态设置颜色。const element = document.querySelector('.color');const colors = ['yellow', 'blue', 'red', 'green']; // The colors you wantconst colorDuration = 200; // The duration of a color in millisecondslet colorIndex = 0;function switchColor() {&nbsp; &nbsp; element.style.color = colors[colorIndex++ % colors.length];}switchColor();setInterval(switchColor, colorDuration);<h1 class="color">Hello world, I love you all.</h1>

侃侃无极

您可以将所有颜色存储在一个数组中,然后使用增量变量为颜色分配索引。你也可以使用 setInterval 而不是 setTimeout。function button_selection() {&nbsp; &nbsp; let colors = ["yellow", "blue", "red", "green"];&nbsp; &nbsp; let index = 0;&nbsp; &nbsp; $(".color").css("color", colors[index]);&nbsp; &nbsp; setInterval(() => {&nbsp; &nbsp; &nbsp; &nbsp; ++index;&nbsp; &nbsp; &nbsp; &nbsp; if (index >= colors.length) index = 0;&nbsp; &nbsp; &nbsp; &nbsp; $(".color").css("color", colors[index]);&nbsp; &nbsp; }, 1000);}setTimeout(button_selection, 0);<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><h1 class="color">Hello world, I love you all.</h1>

守候你守候我

创建一个数组并将键/值对分配给您要迭代的值。然后用于$.each()在您的函数中迭代该数组。function button_selection() {&nbsp; &nbsp; setTimeout(button_selection, 800);&nbsp; &nbsp; let colors = {"yellow": 200, "blue": 400, "red": 600, "green": 800};&nbsp; &nbsp; $.each( colors, function( key, value ) {&nbsp; &nbsp; &nbsp; setTimeout(function () { $(".color").css("color", key); }, value);&nbsp; &nbsp; });&nbsp; &nbsp;&nbsp;}setTimeout(button_selection, 0);<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><h1 class="color">Hello world, I love you all.</h1>

绝地无双

我会选择这个const colors = ['yellow', 'green', 'blue', 'red']const INTERVAL = 200;colors.forEach((color, index) => {&nbsp; setTimeout(() => { $('.color').css("color", colors[index]) }, index*INTERVAL)&nbsp;})<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script><h1 class="color">Hello world!<h1>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript