如何隐藏除第一个外的所有<h2>标签?

3
我应该如何隐藏所有 <h2>,除了第一个?
<div class="holder">
  <h2>SOme heading</h2>
  <h2>Some Heading<h2>
  <h2>Some Heading<h2>
  <h2>Some Heading<h2>
  <h2>Some Heading<h2>
</div>

我知道我们可以使用类似以下的内容:

p:nth-child(2)
{
  display:none;
}

但不确定如何隐藏除第一个之外的所有内容。有没有人能指导一下?希望有一个跨浏览器兼容的解决方案。

6个回答

10

1
成功了!这个在不同的浏览器上都兼容吗? - ariel
这个能用 JQuery 实现吗? - ariel
@ariel 当然可以。你想让我写点什么吗? - Josh Crozier
@ariel 这里有一个例子,展示了三个不同的选择器,它们都可以正常工作。它们在IE6+中都能正常工作.. 我相信它也可以在IE6中工作,尽管我无法测试。 - Josh Crozier
谢谢,你能分享一下你提到的另一个CSS解决方案吗?它是否兼容跨浏览器?由于其他JS冲突,我在页面中使用JQuery时遇到了问题。非常感激。谢谢。 - ariel
显示剩余2条评论

2

2

1
h2:not(:first-child) {
    display: none;
}

0

查看这个fiddle

这里有一个选项,使用:not伪选择器与:first-child伪选择器相结合。

div.holder h2:not(:first-child) {
  display: none;
}

0
假设标题之间可能有其他标签,使用现代CSS,我们可以这样编写:
h2:not(:first-of-type) { display: none; }

或者

h2:nth-of-type(n+2) { display: none; }

要使代码与IE8兼容,我们可以使用以下方法,类似于JoshC的答案:

.holder h2 ~ h2 { display: none; }

但是为什么代码中需要有许多不可见的标题呢?这似乎对搜索引擎不利...


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接