这是 Jsfiddle这显示了我到目前为止所拥有的。我希望这样当用户将鼠标悬停在背景颜色为红色的 div 上时,setInterval 应该停止,以便鼠标悬停在它上面的 div 应该保持红色,所有其余的 div 保持默认颜色(白色)。
当鼠标离开 div 时,设置的时间间隔继续。
function bgChange(){
for(var count = 0; count < arr.length; count++){
if(i == count) arr[count].css('background-color', "red");
else arr[count].css("background-color", "skyblue");
}
i++;
if( i === arr.length){i =0;}
var color = $(".boxes").each(function(){//part of the code i
// tried adding but doesnt't work
$(this).css("background-color")
})
console.log(color)
//check the background color to see if its red. Also if the mouse is over the
//particular div it should clear the interval and when the mouse moves out of the
// the div it should start rotating colors down the row
}
JSFIDDLE提前致谢。
最佳答案
这个怎么样?我正在添加/删除一个 css 类,而不是直接设置背景颜色。然后在 mousover 上,如果设置了红色类,则停止间隔,并在 mouseout 上再次启动间隔。 setInterval 调用必须保存为变量,以便稍后清除它。
$(document).ready(function () {
var arr = [];
var i = 0;
$(".boxes").each(function () {
arr.push($(this));
});
function bgChange() {
for (var count = 0; count < arr.length; count++) {
if (i == count) arr[count].addClass('red');
else arr[count].removeClass('red');
}
i++;
if (i == arr.length) i = 0;
}
var interval = setInterval(bgChange, 2000);
$(".boxes").mouseover(function(){
if($(this).hasClass('red')){
clearInterval(interval);
}
});
$(".boxes").mouseout(function(){
if($(this).hasClass('red')){
interval = setInterval(bgChange, 2000);
}
});
});
关于javascript - 悬停时 clearInterval 并且如果元素具有特定背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18817530/