显示部分/格取决于链接

时间:2019-02-12 07:13:02

标签: html css

我有以下页面

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

如果用户来自包含哈希后的部分ID的链接,例如

,则可以使用html / css仅显示一个部分

3 个答案:

答案 0 :(得分:6)

您可以研究: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>

答案 1 :(得分:2)

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>

答案 2 :(得分:2)

我的解决方案不包含HTML嵌套,并且可以轻松扩展。它使用:targetgeneral sibling combinator查找匹配项并仅显示目标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> -->