5
    function hoverOpacity() {
    $('#fruit').mouseover(function() {
        $(this).animate({opacity: 0.5}, 1500);
      });
    $('#fruit').mouseout(function() {
        $(this).animate({opacity: 1}, 1500);
      });
}

这是我的动画功能,div#fruit它确实有效。

问题是这样的;当你mouseoutmousein动画结束之前,它必须在开始之前完成动画mouseout。(希望这是有道理的)

这通常不明显,但持续时间较长时,它是明显的。

我希望动画停止并反转到原始状态,而不是完成动画。

4

4 回答 4

6

您正在寻找该stop功能,可能后跟show(或hide,或css,取决于您想要opacity结束的状态)。

function hoverOpacity() {
    $('#fruit').mouseover(function() {
        $(this).stop(true).animate({opacity: 0.5}, 1500);
      });
    $('#fruit').mouseout(function() {
        $(this).stop(true).animate({opacity: 1}, 1500);
      });
}

true告诉动画跳到最后。如果这是元素上唯一的动画,那应该没问题;否则,正如我所说,您可以查看css明确设置所需的不透明度。

但是,另外,您可能会考虑使用mouseenterandmouseleave而不是mouseoverand mouseout,原因有两个:1.mouseover鼠标在元素上移动时重复,以及 2.mouseovermouseout bubble,所以如果你的“fruit”元素有子元素,你'也会从它们那里接收事件,这往往会破坏这种动画的稳定性。

于 2011-05-18T10:57:19.877 回答
2

您需要.stop()在动画之前添加一个调用以清除当前和任何排队的动画:

function hoverOpacity() {
    $('#fruit').mouseover(function() {
        $(this).stop(true).animate({opacity: 0.5}, 1500);
      });
    $('#fruit').mouseout(function() {
        $(this).stop(true).animate({opacity: 1}, 1500);
      });
}
于 2011-05-18T10:57:02.450 回答
1

尝试这个:

function hoverOpacity() {
    $('#fruit').mouseover(function() {
        $(this).stop(true, true).animate({opacity: 0.5}, 1500);
      });
    $('#fruit').mouseout(function() {
        $(this).stop(true, true).animate({opacity: 1}, 1500);
      });
}

这应该停止动画,清除队列(第一个参数)并跳到最后(第二个参数),您可以根据需要更改/弄乱参数。

于 2011-05-18T10:56:43.727 回答
0

也试试这个:

function hoverOpacity() {
    $('#fruit').hover(function() {
        $(this).animate({opacity: 0.5}, 1500);
    }, function() {
        $(this).animate({opacity: 1}, 1500);
    });
}
于 2011-05-18T10:58:00.697 回答