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

return an element to its starting position after .stop() is activated

本文关键字:返回 位置 元素 stop 激活      更新时间:2023-09-26

我正在写一个非常酷的jquery插件,我发现自己在最后一点上陷入困境。 基本上,我在mouseenter和mouseleave上对元素进行动画处理。在这个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 );
});

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

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

。但它可能有点跳跃。

或者,正如您所说,你知道元素从哪里开始,只需将其返回到那里:

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

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

或者,同样,当您拥有原始位置时,您可以动画化回该位置(或前进到该位置 + 100px,具体取决于)。