javascript - jQuery 的 .hide() 和设置 CSS 显示 : none 的区别

标签 javascript jquery html css show-hide

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

最佳答案

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

"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(),因为这样之前的状态就是记得。除此之外没有区别。

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

关于javascript - jQuery 的 .hide() 和设置 CSS 显示 : none 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4396983/

相关文章:

javascript - jQuery 中令人困惑的wrappAll

javascript - 如何在 iframe 中打开页面时隐藏按钮?

javascript - 当 DOM 在 iOS 中准备就绪时,如何强制关注文本字段?

javascript - 如何根据条件附加gapi-auth2.attach Click Handler

JavaScript : "event is sent to an element" -

javascript - 在 IOS 设备上填充快速类型栏选项

javascript - vue.js 中多个导入和注册的组件

javascript - Opera 中的 HTML5 文件阅读器

html - 使用 flexbox 将一个元素居中对齐,同时将其唯一的兄弟元素右对齐

javascript - 更改 Javascript 中的单位