window.location.href和window.locaiton.hash
(1)window.location.href 得到的是完整的URL
比如:window.location.href = ' www.baidu.com'
(2)window.location.hash 得到的是錨連結
比如:window.location.hash= ' #all'
(3)window.location.search得到的是URL‘?’号後面的字元串部分
www.baidu.com/?username=aaa&age=10
比如:window.location.search= ' ?username=aaa&age=10'
hash 屬性 即URL字元串中從#号開始的部分(從 # 号開始的部分)。
(1)使用浏覽器通路網頁時,如果網頁url中帶有hash ‘#123’,那麼頁面就會定位到id或者name為123的元素的位置;
(2)hash改變的話,不會導緻頁面重新加載(頁面隻需要一次加載,速度快);
window.location.hash值的變化以及浏覽器位址欄(#号後面的值發生變化)任何一方發生變化,都會觸發onhashchange事件
hashchange事件
window.addEventListener('hashchange',function(){
console.log(111);
});
addEventListener() 方法,事件監聽,你也可以使用removeEventListener()方法來移除事件監聽;
element.addEventListener(event,fun,bool);
(1)event: 事件類型(如‘click’)
(2)fun: 事件觸發後的回調函數;
(3)bool:布爾值,用于描述事件是冒泡還是捕獲,可選;
Demo(利于hash實作标簽頁(tab頁))
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>hash</title>
<script src="js/jquery-1.11.3.min.js"></script>
<style>
*{
margin:0; padding:0;
}
body{
margin:100px;
}
a{
text-decoration: none;
color:#fff;
}
.task-list{
list-style: none;
overflow: hidden;
width: 500px;
margin:auto;
padding: 10px;
border:1px solid #DCDCDC;
border-bottom:none;
background: #2aabd2;
}
.task-list li{
float: left;
margin-right: 30px;
}
.task-list li>a{
padding:10px 15px;
}
.task-content{
width: 500px;
margin:auto;
height:300px;
padding: 10px;
border:1px solid #DCDCDC;
}
.task-content div{
display: none;
padding: 15px;
}
.task-content div.active{
display: block;
}
</style>
</head>
<body>
<ul class="task-list">
<li><a href="#all" target="_blank" rel="external nofollow" >所有任務</a></li>
<li><a href="#unfinished" target="_blank" rel="external nofollow" >未完成任務</a></li>
<li><a href="#finished" target="_blank" rel="external nofollow" >完成任務</a></li>
</ul>
<div class="task-content">
<div id="all" class="active">所有任務11</div>
<div id="unfinished">未完成任務22</div>
<div id="finished">完成任務33</div>
</div>
<script>
var hashStr;
function watchHash(){
var hash = window.location.hash.slice(1);
hashStr = hash;
console.log(hashStr);
if(hashStr){
$('#'+hashStr).show();
$('#'+hashStr).siblings().hide();
}
}
watchHash();
window.addEventListener("hashchange",watchHash);
</script>
</body>
</html>
附圖: