首页 文章

如何使用jQuery在悬停时循环显示背景颜色

提问于
浏览
0

我'm trying to make a div that cycles through background colors when hovered over with the mouse. I'已经想出如何使背景颜色从 mouseenter 上的一组值切换到颜色值,但不知道如何让它继续运行 .

当鼠标悬停在元素上时,如何让背景颜色不断变化(一旦我被淘汰就停止)?

到目前为止,这是一个完全正常工作的小提琴:FIDDLE

我的HTML:

<body>  
    <div id="coloredDiv" data-index="-1"></div>
</body>

我的CSS:

#coloredDiv {
    width:200px;
    height:200px;
    border:1px solid #888;
}

#coloredDiv:hover {
    cursor:pointer;
}

我的jQuery:

var colors = ['#eeeeee', "#00ff00", "#ff0000", "#000000"];

$(document).ready(function () {
    $colorDiv = $('#coloredDiv');
    ln = colors.length;
    $('#coloredDiv').mouseenter( function () {
        var i = $colorDiv.data("index");
        ++i;
        if (i >= ln) i = 0;
        $colorDiv.css({
            'background-color': colors[i]
        });
        $colorDiv.data("index", i);
    });
});

2 回答

  • 3

    使用 Array.shiftArray.push 进行循环

    小提琴

    var counter = 0;
    var colors = [
        "#eeeeee",
        "#00ff00",
        "#ff0000",
        "#000000"];
    
    var $div = $('#coloredDiv');
    
    $('#coloredDiv').mouseenter(function () {
        var color = colors.shift(); //Get the top color
        colors.push(color); //push it to the end for the cycle to repeat.
        $div.css({
            "background-color": color
        })
    
    });
    

    要在悬停时重复循环: -

    var counter = 0;
    var colors = [
        "#eeeeee",
        "#00ff00",
        "#ff0000",
        "#000000"];
    
    var $div = $('#coloredDiv');
    var interval;
    $('#coloredDiv').mouseenter(function () {
        interval = window.setInterval(changeColor, 1000); //set the interval of 1 sec for image to change while hovered.
    
    }).mouseleave(function () {
        window.clearInterval(interval); //clear the interval on mouseOut.
    });
    
    function changeColor() {
        var color = colors.shift();
        colors.push(color);
        $div.css({
            "background-color": color
        });
    
    }
    

    小提琴

  • 1
    (function() {
      var element = $('#id');
      var colors = ['#eeeeee', "#00ff00", "#ff0000", "#000000"];
      var idx = 0;
      var timer;
    
      function changeColor() {
        element.css('background-color', colors[idx++ % colors.length]);
      }
    
      element.hover(
        // start hover
    
        function() {
          idx = 0;
          changeColor();
          timer = setInterval(changeColor, 250);
        },
    
        // end hover
    
        function() {
          clearInterval(timer);
          element.css('background-color', '');
        }
      );
    }());
    

相关问题