javascript - 悬停时 clearInterval 并且如果元素具有特定背景

标签 javascript jquery html css

这是 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/

相关文章:

javascript - node-qunit 不在范围内包含我的源文件

javascript - jQuery Cycle 插件 : centering background images when browser is resized

javascript - 删除标记谷歌地图API。为什么缩放时再次显示标记?

javascript - 如何更改文本区域中文本的颜色

php - jQuery 自动完成标记新标签设计模式

php - div 中的按钮

html - 删除 HTML CSS 中的下划线格式

html - 在固定宽度容器内居中绝对元素

javascript - 使用 blob 作为源图像

jquery - 在移动元素上不要触发鼠标事件