我最好做什么? .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/