4 回答
TA贡献1772条经验 获得超6个赞
你不需要 jQuery。制作一个计数器,每n毫秒递增一次,并根据计数器状态设置颜色。
const element = document.querySelector('.color');
const colors = ['yellow', 'blue', 'red', 'green']; // The colors you want
const colorDuration = 200; // The duration of a color in milliseconds
let colorIndex = 0;
function switchColor() {
element.style.color = colors[colorIndex++ % colors.length];
}
switchColor();
setInterval(switchColor, colorDuration);
<h1 class="color">Hello world, I love you all.</h1>
TA贡献2051条经验 获得超10个赞
您可以将所有颜色存储在一个数组中,然后使用增量变量为颜色分配索引。
你也可以使用 setInterval 而不是 setTimeout。
function button_selection() {
let colors = ["yellow", "blue", "red", "green"];
let index = 0;
$(".color").css("color", colors[index]);
setInterval(() => {
++index;
if (index >= colors.length) index = 0;
$(".color").css("color", colors[index]);
}, 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>
TA贡献1802条经验 获得超10个赞
创建一个数组并将键/值对分配给您要迭代的值。然后用于$.each()在您的函数中迭代该数组。
function button_selection() {
setTimeout(button_selection, 800);
let colors = {"yellow": 200, "blue": 400, "red": 600, "green": 800};
$.each( colors, function( key, value ) {
setTimeout(function () { $(".color").css("color", key); }, value);
});
}
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>
TA贡献1946条经验 获得超4个赞
我会选择这个
const colors = ['yellow', 'green', 'blue', 'red']
const INTERVAL = 200;
colors.forEach((color, index) => {
setTimeout(() => { $('.color').css("color", colors[index]) }, index*INTERVAL)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<h1 class="color">Hello world!<h1>
添加回答
举报