我'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 回答
使用
Array.shift
和Array.push
进行循环小提琴
要在悬停时重复循环: -
小提琴