4.2 隐藏和显示元素

基本的.hide().show()方法不带任何参数。可以把它们想象成类似.css('display','string')方法的简写方式,其中string是适当的显示值。不错,这两个方法的作用就是立即隐藏或显示匹配的元素集合,不带任何动画效果。

其中,.hide()方法会将匹配的元素集合的内联style属性设置为display:none。但它的聪明之处是,它能够在把display的值变成none之前,记住原先的display值,通常是blockinlineinline-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链接:

  1. <div class="speech">
  2. <p>Fourscore and seven years ago our fathers brought forth
  3. on this continent a new nation, conceived in liberty,
  4. and dedicated to the proposition that all men are
  5. created equal.
  6. </p>
  7. <p>Now we are engaged in a great civil war, testing whether
  8. that nation, or any nation so conceived and so dedicated,
  9. can long endure. We are met on a great battlefield of
  10. that war. We have come to dedicate a portion of that
  11. field as a final resting-place for those who here gave
  12. their lives that the nation might live. It is altogether
  13. fitting and proper that we should do this. But, in a
  14. larger sense, we cannot dedicate, we cannot consecrate,
  15. we cannot hallow, this ground.
  16. </p>
  17. <a href="#" class="more">read more</a>
  18. ...
  19. </div>

当DOM就绪时,选择一个元素并调用.hide()方法,参见代码清单4-6。

代码清单4-6

  1. $(document).ready(function() {
  2. $('p').eq(1).hide();
  3. });

这里的.eq()方法与第2章中讨论的:eq()伪类相似。这个方法返回jQuery对象,其中包含一个元素(索引从0开始)。在这个例子中,.eq()方法选择第二个段落并隐藏该段落,结果看起来如图4-3所示。

4.2 隐藏和显示元素 - 图1

图 4-3

然后,当用户单击第一段末尾read more链接时,就会隐藏该链接同时显示第二个段落,参见代码清单4-7。

代码清单4-7

  1. $(document).ready(function() {
  2. $('p').eq(1).hide();
  3. $('a.more').click(function(event) {
  4. event.preventDefault();
  5. $('p').eq(1).show();
  6. $(this).hide();
  7. });
  8. });

注意,这里使用了.preventDefault()来避免链接的默认操作,此时的讲话文本如图4-4所示。

4.2 隐藏和显示元素 - 图2

图 4-4

虽然.hide().show()方法简单实用,但它们没有那么花哨。为了增添更多的艺术感,我们可以为它们指定速度。