动画完成后元素不被隐藏

Elements not being hidden after animation is complete

我这辈子都弄不明白为什么我 运行 这个函数没有隐藏元素。当鼠标悬停在一个列表项上时,我希望其中的两个 div 动画到 49% 高度,当鼠标离开此列表项时,它们会返回 0 并再次获得 display: none;。然而,即使执行了 animate 的回调函数中的语句,它们仍然停留在 display: block; 处。

下面是它们动画到 49% 时的样子:

这是他们回到 0 的时间:

由于某些原因,回调中的 .hide() 函数没有隐藏包含图像的两个 div 元素。

这是不起作用的功能:

$('#site-wrapper').on('mouseenter', '#images-list li', function() {

    $(this).children('div').show().stop().animate({height: '49%'}, 'fast');
}).on('mouseleave', '#images-list li', function() {

    $(this).children('div').stop().animate({height: 0}, 'fast', function() {
        $(this).children('div').hide();
    });
});

这个解决方案有效,但它会立即隐藏它,用户无法看到我不想要的动画:

$('#site-wrapper').on('mouseenter', '#images-list li', function() {

    $(this).children('div').show().stop().animate({height: '49%'}, 'fast');
}).on('mouseleave', '#images-list li', function() {

    $(this).children('div').stop().animate({height: 0}, 'fast').hide();
});

我应该怎么做才能解决这个相当愚蠢的错误?

你能试试这个吗?最好使用 fiddle 来证明这一点:

$('#site-wrapper').on('mouseenter', '#images-list li', function() {
    $this = $(this);
    $this.children('div').show().stop().animate({height: '49%'}, 'fast');
}).on('mouseleave', '#images-list li', function() {
    $this.children('div').stop().animate({height: 0}, 'fast', function() {
        $this.children('div').hide();
    });
});

来自 .animate() 上的文档(强调我的)

Complete Function

If supplied, the complete callback function is fired once the animation is complete. This can be useful for stringing different animations together in sequence. The callback is not sent any arguments, but this is set to the DOM element being animated.

所以

...
.on('mouseleave', '#images-list li', function() {
    $(this).children('div').stop().animate({height: 0}, 'fast', function() {
        $(this).children('div').hide(); // Wrong line
    });
});

应该是

...
.on('mouseleave', '#images-list li', function() {
    $(this).children('div').stop().animate({height: 0}, 'fast', function() {
        $(this).hide(); // Hide the same div that was animated
    });
});