Jquery改变不同的背景

时间:2013-06-22 18:08:39

标签: javascript jquery

我有跟随Jquery代码...按钮点击它改变了一些间隔的背景颜色...当我第二次点击按钮时我想要的东西(第3和等等)它开始显示最后到达时的下一堆颜色它应该停在每一组的最后颜色...抱歉要求更详细的帮助。

$(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/

提前感谢!

1 个答案:

答案 0 :(得分:2)

这对我来说并不完全清楚,但如果我理解了你的问题,这应该可以解决问题(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);
    });
});
相关问题