4.2 隐藏和显示元素
基本的.hide()
和.show()
方法不带任何参数。可以把它们想象成类似.css('display','string')
方法的简写方式,其中string
是适当的显示值。不错,这两个方法的作用就是立即隐藏或显示匹配的元素集合,不带任何动画效果。
其中,.hide()
方法会将匹配的元素集合的内联style
属性设置为display:none
。但它的聪明之处是,它能够在把display
的值变成none
之前,记住原先的display
值,通常是block
、inline
或inline-block
。恰好相反,.show()
方法会将匹配的元素集合的display
属性,恢复为应用display: none
之前的可见属性。
关于display
属性
要了解有关display
属性及其不同的值在网页中的视觉表现,请访问Mozilla Developer Center的相关页面,网址为https://developer.mozilla.org/en/CSS/display/,或到https://developer.mozilla.org/samples/cssref/display.html查看相关示例。
.show()
和.hide()
的这种特性,使得它们非常适合隐藏那些默认的display
属性在样式表中被修改的元素。例如,在默认情况下,<li>
元素具有display:list-item
属性。但是,为了构建水平的导航菜单,它们可能会被修改成display:inline
。而在类似这样的<li>
元素上面使用.show()
方法,不会简单地把它重置为默认的display:list-item
,因为那样会把<li>
元素放到单独的一行中;相反,.show()
方法会把它恢复为先前的display:inline
状态,从而维持水平的菜单设计。
要示范这两个方法,最明显的例子就是在前面的HTML中再添加一个新段落,然后在第一个段落末尾加上一个read more链接:
<div class="speech">
<p>Fourscore and seven years ago our fathers brought forth
on this continent a new nation, conceived in liberty,
and dedicated to the proposition that all men are
created equal.
</p>
<p>Now we are engaged in a great civil war, testing whether
that nation, or any nation so conceived and so dedicated,
can long endure. We are met on a great battlefield of
that war. We have come to dedicate a portion of that
field as a final resting-place for those who here gave
their lives that the nation might live. It is altogether
fitting and proper that we should do this. But, in a
larger sense, we cannot dedicate, we cannot consecrate,
we cannot hallow, this ground.
</p>
<a href="#" class="more">read more</a>
...
</div>
当DOM就绪时,选择一个元素并调用.hide()
方法,参见代码清单4-6。
代码清单4-6
$(document).ready(function() {
$('p').eq(1).hide();
});
这里的.eq()
方法与第2章中讨论的:eq()
伪类相似。这个方法返回jQuery对象,其中包含一个元素(索引从0开始)。在这个例子中,.eq()
方法选择第二个段落并隐藏该段落,结果看起来如图4-3所示。
图 4-3
然后,当用户单击第一段末尾read more链接时,就会隐藏该链接同时显示第二个段落,参见代码清单4-7。
代码清单4-7
$(document).ready(function() {
$('p').eq(1).hide();
$('a.more').click(function(event) {
event.preventDefault();
$('p').eq(1).show();
$(this).hide();
});
});
注意,这里使用了.preventDefault()
来避免链接的默认操作,此时的讲话文本如图4-4所示。
图 4-4
虽然.hide()
和.show()
方法简单实用,但它们没有那么花哨。为了增添更多的艺术感,我们可以为它们指定速度。