为什么鼠标输入动画附加到子对象而不仅仅是父对象



我有一个jquery动画,它是由父对象()上的鼠标输入触发的,但如果用户"摆动"子对象()的鼠标,动画会闪烁,就好像它在鼠标输出和鼠标输入之间切换一样。

在父对象上调用mouseenter。为什么它也附着在孩子身上,我能防止这种情况发生吗?

示例:

http://jsfiddle.net/uqgz9/

我已经研究了.stopImmediatePropagation();和.stopPropagation();我认为这可能是正确的方向,但无法获得我需要的互动。

谢谢。

使用.mouseleave()而不是.mouseout()

http://jsfiddle.net/uqgz9/4/

var imgW;
$('.brand-box-item').mouseenter(function(){
    if($(this).find('img').is(':animated') === false)
        imgW = $(this).find('img').width();        
    $(this).find('img').stop().animate({'width':'0','margin-left':(imgW/2)+'px'},function(){
        $(this).css({'margin-top':'-40px'});
        $(this).stop().animate({'width':imgW+'px','margin-left':'0'});
    });
});
$('.brand-box-item').mouseleave(function(){
    $(this).find('img').stop().animate({'width':'0','margin-left':(imgW/2)+'px'},function(){
        $(this).css({'margin-top':'0'});
        $(this).animate({'width':imgW+'px','margin-left':'0'});
    });
});

"mouseleave事件与mouseout的不同之处在于它处理事件冒泡的方式。如果在本例中使用mouseout,那么当鼠标指针移出Inner元素时,处理程序就会被触发。这通常是不可取的行为。另一方面,mouseleaf事件只在鼠标离开绑定到的元素时触发其处理程序,而不是子代例如,当鼠标离开Outer元素而不是Inner元素时,会触发处理程序。"-jQuery文档

如果您将此代码添加到事件中,则如果目标元素不是选择器的一部分,它将停止事件:

if (!$(e.target).is(this)) {
    return false;
}

演示:http://jsfiddle.net/uqgz9/3/

该事件仍然会触发,因为鼠标经过父元素的边界,这会很快触发该事件。

@nbrooks在接受的答案中说了什么,加上代码将简化如下:

$('.brand-box-item').on('mouseenter mouseleave', function() {
    var imgW,
        $img = $(this).find('img');
    if (!$img.is(':animated')) {
        imgW = $img.width();
        $img.stop().animate({
            'width': 0,
            'margin-left': imgW / 2
        }, function() {
            $img.css({
                'margin-top': -40
            }).stop().animate({
                'width': imgW,
                'margin-left': 0
            });
        });
    }
});

演示

在IE9和Opera 12.01 中测试

相关内容

最新更新