HTML中有多个页面,而且没有JS

5 html css css3

我见过一些网站使用CSS来改变页面而不使用javascript,他们使用hashtag来记住用户正在查看的页面.
输入url example.com/#page1的示例会显示page1等.

我用CSS和javascript做了一个例子,但如上所述,我想得到相同的结果,但只有CSS.

我的代码:

<head>
<style>
#content2 {
display:none;
}
</style>
</head>

<body>
<a href ="#link1" id="link1">Link 1</a>
<a href ="#link2" id="link2">Link 2</a>

<div id="content1">
Content of page 1 (Link 1)
</div>

<div id="content2">
Content of page 2 (Link 2)
</div>

<script>
var hash = window.location.hash;
// Show a page based on # ( so a user can LINK to a specific page)

//Page 1
if(hash == "#link1") {
$("#content1").css("display","block");
}
$("#link1").click(function() {
$("#content1").show();
$("#content2").hide();
});

//Page2
if(hash == "#link2") {
$("#content2").css("display","block");
}
$("#link2").click(function() {
$("#content2").show();
$("#content1").hide();
});
</script>
</body>
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/dq90d8ry/

Bho*_*yar 0

您可以使用:target 伪类:

让我们看一个例子。(示例摘自w3.org

它有一些带有相应 ID 的链接和元素:

<p>
  <a href="#item1">item 1</a>
  <a href="#item2">item 2</a>
  <a href="#item3">item 3</a>
  <a href="#default">clear</a>

<div class="items">
  <p id="item1">... item 1...
  <p id="item2">... item 2...
  <p id="item3">...
  <p id="default"><!-- by default, show no text -->
</div>
Run Code Online (Sandbox Code Playgroud)

样式规则首先隐藏 DIV 内的所有 P,然后覆盖当前目标 P 的规则:

div.items p {display: none}
div.items p:target {display: block}
Run Code Online (Sandbox Code Playgroud)

就这样。

实际上,我们添加了“:not(:target)”,以确保只有 CSS3 浏览器才会隐藏该元素。所以更好的规则是:

div.items p:not(:target) {display: none}
div.items p:target {display: block}
Run Code Online (Sandbox Code Playgroud)