首页 > 解决方案 > John Doe no-js 网页中的 css 究竟是如何使默认主页部分消失的?

问题描述

我正在查看这个漂亮的最小 Web 模板:https ://john-doe.neocities.org/(这里的github:https ://github.com/cadars/john-doe/ )

这使用 section 标签和 :target 选择器优雅地创建 no-js 'tabs',使一个特定的部分可见,同时隐藏页面中的所有其他部分。

我尝试通过以下简化的 css 为我的网站重现此内容:

section { display: none; }
section:target { display: block; }
section#home { display:block;}

但是,这并没有达到预期的效果,因为虽然它确实实现了“默认”部分将在 url 中没有 #reference 的情况下显示的效果,但是当指定另一个引用时它不会隐藏它. 换句话说,总是显示带有“home”id 的部分,无论它是否是目标。

而在 John Doe 页面中,您将看到如果选择了任何其他目标,则会替换 #home 部分。如果没有选择任何部分(即 URL 不包含“#”引用),默认情况下 #home 元素确实是可见的。

我在 John Dow 网站上研究了 css 样式,但我看不出我的 css 和 John Doe 的 css 有什么区别,这使得它们的默认 #home 部分按预期运行。有人可以帮我弄清楚吗?

这是一个简单的测试用例:

<html>
  <head>
    <style>
      section { display: none; }
      section:target { display: block; }
      section#first { display: block; }
    </style>
  </head>
  <body>
    <section id="first" > First (default) section </section>
    <section id="second"> Second section          </section>
    <section id="third" > Third section           </section>
  </body>
</html>

我错过了什么?

标签: htmlcss

解决方案


你可以这样做:

section:target {
  display: block; /* show the targetted one */
}

section:target ~ section, /* all the section after the targetted one hidden*/
section { /* all of them hidden */
  display: none;
}

section:last-of-type {
  display: block; /* last one visible */
}
<section id="second"> Second section </section>
<section id="third"> Third section </section>
<section id="first"> First (default) section </section> <!-- must be the last one -->
<div style="position:absolute;top:10px;right:10px;">
  <a href="#first">first</a>
  <a href="#second">second</a>
  <a href="#third">third</a>
</div>

或者像下面这样:

section:target {
  display: block;
}

section:target ~ section:not(#random),
section {
  display: none;
}

section#first {
  display: block;
}
<section id="second"> Second section </section>
<section id="third"> Third section </section>
<section id="first"> First (default) section </section> <!-- must be not the first one (at least one section before it) -->
<div style="position:absolute;top:10px;right:10px;">
  <a href="#first">first</a>
  <a href="#second">second</a>
  <a href="#third">third</a>
</div>


推荐阅读