Jquery 简单DIV悬停动画

Jquery 简单DIV悬停动画,jquery,jquery-animate,mouseleave,Jquery,Jquery Animate,Mouseleave,我正在使用animate()在指针位于DIV上方时向左设置DIV标记的动画。当指针离开DIV标记时,它会将动画设置回其原始位置。这里的问题是,动画在鼠标上方向左移动DIV标记50个像素,在鼠标左侧向右移动50个像素 这使得DIV向右移动50个像素,即使动画未完成 $('body').on('mouseenter', '.image-photo-previous', function() { $(this).animate({marginLeft: '-=50px'}, 300, 'swi

我正在使用
animate()
在指针位于DIV上方时向左设置DIV标记的动画。当指针离开DIV标记时,它会将动画设置回其原始位置。这里的问题是,动画在鼠标上方向左移动DIV标记50个像素,在鼠标左侧向右移动50个像素

这使得DIV向右移动50个像素,即使动画未完成

$('body').on('mouseenter', '.image-photo-previous', function() {
    $(this).animate({marginLeft: '-=50px'}, 300, 'swing');
});

$('body').on('mouseleave', '.image-photo-previous', function() {
    $(this).animate({marginLeft: '+=50px'}, {queue: false}, 300, 'swing');
});

即使鼠标离开时动画未完成,如何使DIV标记动画恢复到其原始位置?

如果希望动画不被中断,则必须让jquery在其
fx
队列中管理动画。你明确告诉它不要在这里:

{queue: false}
因此,您需要将其更改为:

$(this).animate({marginLeft: '+=50px'}, {queue: true}, 300, 'swing');
然后它将等待动画离开队列,以开始下一个动画。

尝试以下操作:

$(document).ready(function() {

    $('body').on('mouseenter', '.image-photo-previous', function() {
        $(this).stop(true,true).animate({marginLeft: '-=50px'}, 300, 'swing');
    });

    $('body').on('mouseleave', '.image-photo-previous', function() {
        $(this).stop(true,true).animate({marginLeft: '+=50px'}, {queue: false}, 300, 'swing');
    });

});
$(document).ready(function() {
    $('body').on('mouseenter', '.image-photo-previous', function() {
        startMargin = $(this).css('marginLeft');
        $(this).animate({marginLeft: '-=50px'}, 300, 'swing');
    });

    $('body').on('mouseleave', '.image-photo-previous', function() {
        $(this).stop();
        $(this).animate({marginLeft: ''}, {queue: false}, 300, 'swing');
    });
});
阅读有关.stop()的更多信息:

(不带JS!)您可以使用CSS3
转换来完成此操作:

使用jQuery:

.stop()
方法将防止一些难看的动画生成,并且使用了一点
三元运算符(?:)
就正确了


您的示例不适合您的需要,因为在任何新的活动中,由于添加到当前DIV样式中的
+=
-=
,您都会弄乱一些新添加的边距计算(到未结束的动画),从而导致元素位置不正确,特别是在快速鼠标移动中
stop()
清除该行为,只需严格定义位置:
-50
0
并将它们绑定到当前事件。

如果没有原始值,可以将marginLeft重置为其原始值或“”

另外,调用
$(this.stop()mouseleave
中的code>取消上一个动画

$(document).ready(function() {
    $('body').on('mouseenter', '.image-photo-previous', function() {
        startMargin = $(this).css('marginLeft');
        $(this).animate({marginLeft: '-=50px'}, 300, 'swing');
    });

    $('body').on('mouseleave', '.image-photo-previous', function() {
        $(this).stop();
        $(this).animate({marginLeft: ''}, {queue: false}, 300, 'swing');
    });
});
小提琴:

让我知道这是否是您想要的。

参考:

可以使用以下代码确定是否应用动画

if( $('.image-photo-previous').is(':animated') ) {...}

如果是这样,您可以使用上面链接中的回调函数等待(使用
setTimeOut
)或计算使div返回其原始位置所需的预期边距像素

-1,因为OP询问“即使鼠标离开时动画未完成,如何使div标记动画返回其原始位置?”@肯尼斯-他从来没有说过它不应该完成,只是当它没有完成时,它不能回到它的起点。没错,我解开了-1。让奥普决定这是否是他想要的。道歉!这就更好了!非常感谢:D如果可以的话,我会接受的
if( $('.image-photo-previous').is(':animated') ) {...}