在.stop()激活后将元素返回到其起始位置

时间:2013-09-23 16:26:39

标签: javascript jquery animation

我正在编写一个非常酷的jquery插件,我发现自己最后一点陷入困境。基本上我是在mouseenter和mouseleave上设置一个元素。一个很好的例子可以在this jsbin中找到,除非你在go按钮完成动画之前将鼠标悬停在后退按钮上,它会将图像移出屏幕。假设我知道元素的起始位置,即使动画提前停止,有没有办法让元素不会动画超过其原始位置?我需要使用.stop()作为动画。也许这只是一件容易的东西,我只是在俯视。

来自jsbin链接的代码段:

// Start animation
$( "#go" ).mouseenter(function() {
    $( ".block" ).stop().animate({ left: "+=100px" }, 2000 );
});
// Start animation in the opposite direction
$( "#back" ).mouseenter(function() {
    $( ".block" ).stop().animate({ left: "-=100px" }, 2000 );
});

1 个答案:

答案 0 :(得分:1)

stop接受控制动画如何离开的参数。您可能想要使用.stop(true, true),它会在停止动画时将动画跳到最后:

$( ".block" ).stop(true, true).animate({ left: "+=100px" }, 2000 );

......但它可能有点跳跃。

或者,正如您所说,您知道元素的起始位置,只需将其返回:

$( ".block" ).stop().css(originalPosition).animate({ left: "+=100px" }, 2000 );

...其中originalPosition是一个具有属性lefttop的对象,大概是。这可能有点跳跃,这取决于你的用例的具体情况。

,再次,你有原始位置,你可以回到那个位置(或转发到那个位置+ 100px,取决于)。