.hide()或display:none?jQuery的

ben*_*e89 150 html javascript css jquery show-hide

我最好干什么?.hide()比写出更快.css("display", "none"),但有什么区别,它们实际上对HTML元素做了什么?

Ste*_*ler 202

从关于.hide()的jQuery页面:

"匹配的元素将立即隐藏,没有动画.这大致相当于调用.css('display','none'),除了显示属性的值保存在jQuery的数据缓存中,以便以后显示恢复到它的初始值.如果一个元素的内联显示值,然后被隐藏并显示,它将再次以内联方式显示."

因此,如果您能够恢复到以前的值很重要,那么display最好使用,hide()因为这样会记住以前的状态.除此之外没有区别.

$(function() {
    $('.hide').click(function(){
        $('.toggle').hide();
        setDisplayValue();
    });
    $('.show').click(function(){
        $('.toggle').show();
        setDisplayValue();
    });
});

function setDisplayValue() {
    var display = $('.toggle')[0].style.display;
    $('.displayvalue').text(display);
}
Run Code Online (Sandbox Code Playgroud)
div {
    display: table-cell;
    border: 1px solid;
    padding: 5px;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
    <button class="hide">Hide</button>
    <button class="show">Show</button>
</p>

<div class="toggle">Lorem Ipsum</div>

<p>
    The display value of the div is:
    <span class="displayvalue"></span>
</p>
Run Code Online (Sandbox Code Playgroud)


Nic*_*ver 33

.hide()在设置之前存储前一个 display属性none,因此如果它不是display元素的标准属性,那么您.show()将使用该存储属性作为返回的属性.所以...它做了一些额外的工作,但除非你做了大量的元素,速度差异应该可以忽略不计.


Spi*_*man 13

看看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;
    }
},
Run Code Online (Sandbox Code Playgroud)


see*_*edg 11

他们是一样的东西..hide()调用jQuery函数并允许您向其添加回调函数.所以,.hide()你可以添加一个动画.

.css("display","none")将元素的属性更改为display:none.它与在JavaScript中执行以下操作相同:

document.getElementById('elementId').style.display = 'none';
Run Code Online (Sandbox Code Playgroud)

.hide()函数显然需要更多时间来运行,因为它检查回调函数,速度等...