我尝试使用forEach循环设置随机的背景颜色,但是所有的div都使用相同的计时器获得相同的背景颜色。
这是到codepen的链接。https://codepen.io/McKern/pen/gvoZRp
var bgColors = [
"#260CE8",
"#7D1AFF",
"#A90CE0",
"#385EFF",
"#0F0559",
"#FF37EB"
];
$('.box').each(function(){
timer = setInterval( function() {
randomBgColor = bgColors[Math.floor(Math.random() * bgColors.length)];
randomNum = Math.floor(Math.random() * ((25-10)+1) + 10);
box = $('.box');
$('.box').css('backgroundColor', randomBgColor)
}, 1000);
});发布于 2018-02-18 14:30:23
您也可以使用jQuery.each()中的值
然后更改第一行和最后一行中的3行。
$('.box').each(function(i, l){
timer = setInterval( function() {
randomBgColor = bgColors[Math.floor(Math.random() *
bgColors.length)];
randomNum = Math.floor(Math.random() * ((25-10)+1) + 10);
box = $('.box');
$(l).css('backgroundColor', randomBgColor)
}, 1000);
});https://stackoverflow.com/questions/48848992
复制相似问题