gpt4 book ai didi

javascript - Jquery改变不同的背景

转载 作者:行者123 更新时间:2023-12-02 18:36:41 25 4
gpt4 key购买 nike

我有以下 Jquery 代码...在按钮上单击它会以一定的间隔更改背景颜色...当第二次单击按钮(第三次等)时我想要什么,当到达最后一个按钮时,它开始显示下一组颜色应该停止在每组的最后一种颜色上...抱歉要求太多详细的帮助。

$(document).ready(function(){

$("button").click(function() {
var colors = ['blue', 'green', 'yellow', 'black'],
colorIndex = 0,
$body = $('body');

setInterval(function(){ $body.css('background', colors[colorIndex++ % colors.length])}, 500);
});
});

这是 jsfiddle 链接: http://jsfiddle.net/aash1010/nHKFK/

提前致谢!

最佳答案

我并不完全清楚,但如果我理解了你的问题,这应该可以解决问题( here is the fiddle ):

$(document).ready(function () {
var colorSets = [],
body = $(document.body),
colorSetsIndex = 0, //goes from 0 to the max length of colorSets
colorIndex = 0, //goes from 0 to the max length of the current colorSet
started = false,
intervalId;
//add all the sets you want
colorSets.push(["blue", "green", "yellow"]);
colorSets.push(["grey", "red", "purple"]);
$(document).on('click', 'button', function () {
if (started) return;
started = true;
intervalId = setInterval(function () {
var currentSet = colorSets[colorSetsIndex];
body.css('background', currentSet[colorIndex]);
colorIndex += 1;
if (colorIndex === currentSet.length) {
colorSetsIndex++;
colorIndex = 0;
}
if (colorSetsIndex === colorSets.length) {
var restart = confirm('Restart?');
if (!restart) {
clearInterval(intervalId);
$("button").off('click');
return;
}
colorSetsIndex = 0;
colorIndex = 0;
}
}, 500);
});
});

关于javascript - Jquery改变不同的背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17253802/

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