jQuery隐藏函数: why does speed: 0 still try to animate?

标签 jquery hide

所以我只是尝试调试以下错误:

<script>
$(function() {
    div = $('<div />');
    div.text('test');
    div.hide(0);
    div.appendto('body');
});
</script>

当我执行此命令时,会显示 DIV。即使我隐藏了它(在我们将其添加到 DOM 之前)。 代码如下:

<script>
$(function() {
    div = $('<div />');
    div.text('test');
    div.hide();
    div.appendto('body');
});
</script>

确实隐藏 DIV。

当我进入 jQuery 隐藏函数的源代码时,我看到了这个:

    hide: function( speed, easing, callback ) {
    if ( speed || speed === 0 ) {
        return this.animate( genFx("hide", 3), speed, easing, callback);

    } else {
        for ( var i = 0, j = this.length; i < j; i++ ) {
            var display = jQuery.css( this[i], "display" );

            if ( display !== "none" ) {
                jQuery.data( this[i], "olddisplay", display );
            }
        }

        // Set the display of the elements in a second loop
        // to avoid the constant reflow
        for ( i = 0; i < j; i++ ) {
            this[i].style.display = "none";
        }

        return this;
    }
},

为什么要检查

if ( speed || speed === 0 ) {

特别是,速度 === 0。我假设,当速度为零时。人们可以完全跳过 animate 函数,只添加 display: none;到元素。

ps。我假设由于我们将 dom 中不存在的元素赋予 animate 函数,因此它会失败。没有什么可以制作动画。因此,animate 函数实际上并没有隐藏 DIV。

感谢转发中的任何答案:) 花了大约 10 分钟寻找正确的语法(hide())而不是 hide(0)),但仍然发现它不合逻辑。因此问题:)

最佳答案

如果你想跳过动画,你可以这样做 .hide() ...通过允许.hide(0),您可以将其排队没有持续时间...所以它增加了很多该功能的实用性。

例如:

$(".myElem").delay(2000).hide(0);

这不起作用的地方:

$(".myElem").delay(2000).hide();

....因为 .hide()不带参数不属于任何 fx 队列,并且会立即发生。

关于jQuery隐藏函数: why does speed: 0 still try to animate?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4540639/

相关文章:

javascript - 如何在我的应用程序中组织 jQuery

javascript - 表单重置后禁用“保存/提交”按钮

swift 3 : How to hide status bar without losing height

css - 在移动设备上隐藏图像

javascript - 需要使用字符串滚动到具有相同 ID 的 div,而不使用 anchor 标记

jquery - 如何在表单提交后更改div文本

javascript - 使用 javascript 自己的隐藏类方法

css - 将页眉中包含的 div 之一隐藏在一页中

javascript - 通过 CSS 隐藏括号内的文本?

javascript - 将后缀附加到 Chart.js 数据集?