0

我有以下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/

提前致谢!

4

1 回答 1

2

我并不完全清楚,但如果我理解了你的问题,这应该可以解决问题(这里是小提琴):

$(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);
    });
});
于 2013-06-22T18:11:47.217 回答