我正在实现,如果我刷新页面,它应该激活以前选择的标签(保留选择的标签)。所以我创建了一个简单的 html 页面并添加了一些 jQuery。
但是如果我手动更改 URL,比如 file:///home/2.html#news
到 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
更改规则,它会在每次 #hash
更改 url 时进行评估。
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
关于javascript - 更改 url 不会更改所选的选项卡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40701807/