我正在开发一个单页网站,其中我有多个div显示:none;
我知道如何让它们在点击时可见并隐藏但我想在某个人更改网址时显示或隐藏div
$(document).ready(function(){
var tabId = location.hash; // will look something like "#h-02"
if(tabId){
$(tabId).show(); // this will fired only when url get hash
$(tabId).siblings().hide(); // this will show only targeted tab
// others get hidden
}
此代码适用于从外部调用和页面重新加载但无法重新加载
的情况例如:index.html#about
如果我更改了联系人的更改并输入我将不会更改,除非我刷新我的页面
有人可以帮助我吗
答案 0 :(得分:1)
您必须侦听hashchange
事件,因为只有哈希值更改后浏览器才会重新加载
$(document).ready(function(){
$(window).on('hashchange', function() {
var tabId = location.hash;
if(tabId){
$(tabId).show();
$(tabId).siblings().hide();
}
}).trigger('hashchange');
});
答案 1 :(得分:0)
您可能根本不需要javascript。您可以使用:target
伪类(IE9 +)。看看吧。
CSS:
.chapter {
display: none;
padding: 10px;
}
.chapter:target {
display: block;
}
因此,当例如location.hash为#h-02
时,具有此类ID的元素将被.chapter:target
规则定位。