jQuery的.hide()与将CSS设置为显示之间的区别:无 [英] Difference between jQuery’s .hide() and setting CSS to display: none

查看:77
本文介绍了jQuery的.hide()与将CSS设置为显示之间的区别:无的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Which am I better off doing? .hide() is quicker than writing out .css("display", "none"), but what’s the difference and what are both of them actually doing to the HTML element?

推荐答案

来自jQuery页面中有关 .hide()的页面:

From the jQuery page about .hide():

匹配的元素将立即隐藏,不显示动画.这与调用.css('display','none')大致等效,不同之处在于display属性的值保存在jQuery的数据缓存中,因此display以后可以恢复为其初始值.如果元素的显示值为inline,则将其隐藏并显示,然后将再次以inline显示."

"The matched elements will be hidden immediately, with no animation. This is roughly equivalent to calling .css('display', 'none'), except that the value of the display property is saved in jQuery's data cache so that display can later be restored to its initial value. If an element has a display value of inline, then is hidden and shown, it will once again be displayed inline."

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

So if it's important that you're able to revert to the previous value of display, you'd better use hide() because that way the previous state is remembered. Apart from that there's no difference.

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

function setDisplayValue() {
    var display = $('.toggle')[0].style.display;
    $('.displayvalue').text(display);
}

div {
    display: table-cell;
    border: 1px solid;
    padding: 5px;
}

<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>

这篇关于jQuery的.hide()与将CSS设置为显示之间的区别:无的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆