【发布时间】:2017-08-10 20:43:39
【问题描述】:
我想链接颜色以在悬停时连续更改,但它永远不会按照我想要的方式工作 - 它不会在 mouseleave/hover out 时停止,您可以在此 fiddle 中看到:
var interv;
function changeColors(item) {
interv = setInterval(function() {
$(item).animate({
color: 'red'
}, 1000)
.animate({
color: 'green'
}, 1000);
}, 100);
};
$(document).ready(function() {
$('a')
.mouseenter(function() {
changeColors(this);
})
.mouseleave(function() {
clearInterval(interv);
$(this).removeAttr("style");
});
});
然后我尝试重新创建 comment 的建议,但正如您在 fiddle 中看到的那样,它也不起作用:
$(document).ready(function() {
var interval;
$('a').hover(
function() {
if (interval)
clearInterval(interval);
interval = setInterval(function() {
$('a').animate({
color: 'red'
}, 1000)
.animate({
color: 'green'
}, 1000);
}, 10);
},
function() {
clearInterval(interval);
interval = null;
$(this).removeAttr("style");
}
);
});
【问题讨论】:
-
嗯...您的间隔为 0...它不起作用,因为您在鼠标移出时已将数千个动画排队。它会一直持续到它完成你开始的所有动画。对于这里的工作来说,间隔是错误的工具。
-
见鬼,使用 jquery 动画可能也是错误的工具。您可以单独使用 css 获得相同的效果,并使用类打开/关闭它。 Here's a question asking how to do the animation with css alone,将其与类结合起来应该很容易。
标签: javascript jquery