我见过一些使用CSS而不使用javascript来更改页面的网站,它们使用井号来记住用户正在查看的页面。
输入网址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>
http://jsfiddle.net/dq90d8ry/
最佳答案
您可以使用: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>
样式规则首先将所有P都隐藏在DIV中,然后覆盖作为当前目标的P:
div.items p {display: none}
div.items p:target {display: block}
就这样。
实际上,我们添加了':not(:target)'以确保只有CSS3浏览器会隐藏该元素。因此,更好的规则是:
div.items p:not(:target) {display: none}
div.items p:target {display: block}