jquery - 动画完成后元素不被隐藏

标签 jquery jquery-animate hide

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

这是当它们被动画化为 49% 时的样子:

animation complete image

这是他们回到0的时候:

image of the error that occurrs

两个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', 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();
});

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

最佳答案

来自 .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
    });
});

关于jquery - 动画完成后元素不被隐藏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28384756/

相关文章:

自定义值的 jQuery 动画(不是 CSS 属性)

jquery - 如果 sibling 有一个特定的类,则隐藏一个 div

javascript - 是否有可能知道在 Javascript/jQuery 中呈现的 HTML 的垂直维度?

javascript - 如何使用 Raphael Js 将图像放在圆圈内

javascript - JQuery 动画在 Chrome 中延迟触发

jquery - 使用jquery时添加动画

html - 在简单的 html 中使用 Div 和隐藏选项

使用 "this"的 JavaScript 对象

javascript - 警报 .position() 方法无法正常工作

javascript - 如何维护使用 jquery 生成的受益人的顺序?