0

我正在尝试制作一个在鼠标悬停时循环显示背景颜色的 div。我已经想出了如何使背景颜色从一组值切换到一个颜色值 on 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);
    });
});
4

2 回答 2

3

使用Array.shiftandArray.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
    });

}

小提琴

于 2013-05-26T08:23:31.093 回答
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', '');
    }
  );
}());
于 2013-05-26T08:24:18.177 回答