1、设置锚点特性(以bootstrap中标签页的代码为例)
html:
1 <div> 2 3 <!-- Nav tabs --> 4 <ul class="nav nav-tabs" role="tablist"> 5 <li role="presentation" class="active"><a href="#home" aria-controls="home" role="tab" data-toggle="tab" onclick="home()">Home</a></li> 6 <li role="presentation"><a href="#profile" aria-controls="profile" role="tab" data-toggle="tab" onclick="profile()">Profile</a></li> 7 <li role="presentation"><a href="#messages" aria-controls="messages" role="tab" data-toggle="tab" onclick="message()">Messages</a></li> 8 <li role="presentation"><a href="#settings" aria-controls="settings" role="tab" data-toggle="tab" onclick="setting()">Settings</a></li> 9 </ul> 10 11 <!-- Tab panes --> 12 <div class="tab-content"> 13 <div role="tabpanel" class="tab-pane active" id="home">home</div> 14 <div role="tabpanel" class="tab-pane" id="profile">profile</div> 15 <div role="tabpanel" class="tab-pane" id="messages">message</div> 16 <div role="tabpanel" class="tab-pane" id="settings">setting</div> 17 </div> 18 19 </div>
js:
1 index.js: 2 var currenturl = window.location.href; 3 if(currenturl.indexOf('#')< 1) { 4 window.location.href = currenturl + '#home'; 5 } else { 6 var hreftype = window.location.hash;//#后面的字段 7 $("a[href="+hreftype+"]").click();//触发此a的点击事件 8 } 9 10 profile.js: 11 var currenturl = window.location.href; 12 if(currenturl.indexOf('#')< 1) { 13 window.location.href = currenturl + '#home'; 14 } else { 15 var hreftype = window.location.hash;//#后面的字段 16 window.location.href = (currenturl.split("#"))[0]+'#profile'; 17 18 }
利用锚点方式切换,页面刷新,也会定位至指定的页面,但是如果页面内容过长,出现滚动条时,锚点会定位至点击的a元素,页面不置顶了。
2、利用history.pullState实现
1 index.js: 2 3 var currenturl = window.location.href; 4 if(currenturl.indexOf('?')< 1) { 5 window.location.href = currenturl + '?home'; 6 } else { 7 var hreftype = window.location.search.substr(1);//?后面的字段 8 $("a[href=#"+hreftype+"]").click();//触发此a的点击事件,注意字段拼接# 9 } 10 11 12 profile.js: 13 14 var currenturl = window.location.href; 15 var newUrl = (currenturl.split("?"))[0]; 16 history.pullState('','',newUrl+'?profile');
以上两种方式都能实现标签页刷新指向当前页面,不会跳至默认首页,url改变页面不会自动刷新,但第二种方法更符合实际效果;