显示部分/div 取决于链接中的哈希 # 值之后



>我有以下页面

section {
 height: 1000px;
 background: yellow;
 margin: 50px;
}
<section id="one">Section one</section>
<section id="two">Section two</section>

如果用户来自在哈希后包含部分 id 的链接,则可以使用 html/css 仅显示一个部分,例如

  • 如果用户转到链接 http://my-site/page#one 他应该只看到第一部分
  • 如果用户转到链接 http://my-site/page#two 他应该只看到第二部分
  • 如果用户转到链接 http://my-site/page 他应该看到所有部分

您可以调查:target伪类的使用情况,但是当 URL 哈希为空时,您可能很难显示所有部分。

例如:

section:not(:target) { display:none; }
section:target { display: block }
<a href="#one">One</a>
<a href="#two">Two</a>
<section id="one">Section one</section>
<section id="two">Section two</section>

我的解决方案不包含 HTML 嵌套,可以轻松扩展。它使用:target和一般兄弟组合器来查找匹配项并仅显示目标section

 /* Display all sections initially */
section {
 height: 1000px;
 background: yellow;
 margin: 50px;
}
/* Hide all targeted sections initially */
span:target ~ section {
  display: none;
}
 
/* Display only the targeted section */
span:nth-of-type(1):target ~ section:nth-of-type(1),
span:nth-of-type(2):target ~ section:nth-of-type(2),
span:nth-of-type(3):target ~ section:nth-of-type(3),
span:nth-of-type(4):target ~ section:nth-of-type(4),
span:nth-of-type(5):target ~ section:nth-of-type(5) {
  display: block;
}
<a href="#one">one</a>
<a href="#two">two</a>
<a href="#three">three</a>
<a href="#four">four</a>
<a href="#five">five</a>
<!-- <a href="#n">n</a> -->
<span id="one"></span>
<span id="two"></span>
<span id="three"></span>
<span id="four"></span>
<span id="five"></span>
<!-- <span id="n"></span> -->
<section>Section one</section>
<section>Section two</section>
<section>Section three</section>
<section>Section four</section>
<section>Section five</section>
<!-- <section>Section n</section> -->

也许 JavaScript 是最好的方法,但如果你真的不想使用它,你可以使用 BenM 建议的:target方法与重复的 HTML 结合使用。

如果没有:target,则显示重复的 HTML。当有目标时,您显示目标并隐藏其他所有内容。

喜欢这个:

#one,
#two {
  display: none;
}
#one:target,
#two:target {
  display: block;
}
#one:target ~ div,
#two:target ~ div {
  display: none;
}
<a href="#one">one</a>
<a href="#two">two</a>
<div id="one">Section one</div>
<div id="two">Section two</div>
<div id="one-duplicate">Section one</div>
<div id="two-duplicate">Section two</div>

最新更新