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

时间:2013-05-26 08:18:55

标签: javascript jquery animation

当我用鼠标悬停时,我正试图制作一个循环通过背景颜色的div。我已经想出如何使背景颜色从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 个答案:

答案 0 :(得分:3)

使用Array.shiftArray.push让周期发生

Fiddle

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
    });

}

Fiddle

答案 1 :(得分: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', '');
    }
  );
}());