How to Cycle Through Background Colors on Hover wi

2019-09-08 02:14发布

问题:

I'm trying to make a div that cycles through background colors when hovered over with the mouse. I've figured out how to make the background color switch to a color value from a set of values on mouseenter, but not how to make it keep going.

How do I make the background color keep changing while the mouse is hovered over the element (and stop once I've moused out)?

Here's a fully working fiddle of what I have so far: FIDDLE

My HTML:

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

My CSS:

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

#coloredDiv:hover {
    cursor:pointer;
}

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

回答1:

Use Array.shift and Array.push to make cycle happen

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

});

For cycle to repeat on hover:-

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



回答2:

(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', '');
    }
  );
}());