jQuery Hide功能:为什么速度:0仍然尝试动画?

时间:2010-12-27 17:52:10

标签: 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函数源代码时,我看到了:

    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函数,它就会失败。没有什么可以动画的。因此,动画功能实际上并不隐藏DIV。

感谢前进中的任何答案:)正在搜索大约10分钟的正确语法(hide())而不是hide(0))但仍然发现它不合逻辑。因此问题:)

1 个答案:

答案 0 :(得分:8)

如果你想跳过动画,你只需要.hide() ...同时允许.hide(0),你可以排队 而不用持续时间...因此它为函数增加了很多实用程序。

例如:

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

这在哪里不起作用:

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

....因为没有参数的.hide()不是任何fx队列的一部分,而且会立即发生。