我实现了如果我刷新页面,它应该激活以前选择的选项卡(保留所选选项卡)。所以我创建了一个简单的html页面并添加了一些jQuery。
但如果我像file:///home/2.html#news
那样手动将URL更改为file:///home/2.html#home
它只更改页面的内容,但不更改选定的选项卡。.
这是我的密码。
<body>
<ul>
<li id="first"><a href="#home">Home</a></li>
<li id="second"><a href="#news">News</a></li>
<li id="third"><a href="#contact">Contact</a></li>
<li id="forth"><a href="#about">About</a></li>
</ul>
<p id="home">
home section
</p>
<p id="news">
news section
</p>
<p id="contact">
contact section
</p>
<p id="about">
about section
</p>
</body>
<style>
p{
display: none;
}
:target {
display:block;
border: 2px solid #D4D4D4;
background-color: #e5eecc;
}
</style>
<script type="text/javascript">
$(document).ready(function(){
if(localStorage.getItem("active_state") == null ){
activeStateId = "first";
}
else{
activeStateId = localStorage.getItem("active_state")
}
$('#'+activeStateId).addClass('active');
$('li').click(function(){
$('.active').removeClass('active');
$(this).addClass('active');
localStorage.setItem("active_state", $(this).attr('id'));
});
});
</script>
最佳答案
当你得到链接散列时,你实际上并没有重新加载页面,但是浏览器只是触发那些链接。您依赖于CSS:target
更改规则,每当url上的#hash
更改时,该规则都会求值。
p {
display: none;
}
:target {
display:block;
border: 2px solid #D4D4D4;
background-color: #e5eecc;
}
因此,即使不刷新页面,也可以正确更新所有部分。为了拥有这样的功能,您不需要将任何数据存储到本地或远程计算机,因为您正在对url使用散列。只需使用散列并处理
hashchange
事件,将.activate
类添加到如下链接:$(document).ready(function() {
var hash = window.location.hash;
if(hash.length > 0) {
hash = hash.substring(1);
$('li a[href$='+hash+']').parent().addClass('active');
}
$(window).on('hashchange', function() {
$('.active').removeClass('active');
var hash = window.location.hash
if(hash.length > 0) {
hash = hash.substring(1);
$('li a[href$='+hash+']').parent().addClass('active');
}
});
});
查看我的工作示例:http://zikro.gr/dbg/html/urlhash.html#about