简体   繁体   English

通过遍历数组来动画背景色[jQuery]

[英]Animate background colour by looping through an array [jQuery]

I'm trying to create something simple. 我正在尝试创建一些简单的东西。

When you hover over ul , the background changes colour to the first item in the array. 当您将鼠标悬停在ul ,背景颜色会更改为数组中的第一项。 Next time you hover over ul , the background changes to the second colour in the array. 下次将鼠标悬停在ul ,背景将更改为数组中的第二种颜色。

JSFIDDLE JSFIDDLE

var col = ['red', 'blue', 'green'];

    $('ul').hover(function(){
        $('.container').animate({backgroundColor: 'red'});
    }, function(){
       $('.container').animate({backgroundColor: 'none'});
    });

The following loop takes each colour and writes it to the console. 以下循环获取每种颜色并将其写入控制台。 However, I'm not sure how to marry the for loop with the hoverso each over moves up the array . 但是,我不确定如何将for loop with the hover - 因此每个over都向上移动数组

for (i=0; i<col.length;i++){
    console.log(col[i]);
}

Use an index like 使用类似的索引

var col = ['red', 'blue', 'green'],
    index = 0;

$('ul').hover(function () {
    $('.container').stop(true).animate({
        backgroundColor: col[index++ % col.length]
    });
}, function () {
    $('.container').stop(true).animate({
        backgroundColor: 'none'
    });
});

Demo: Fiddle 演示: 小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM