window.location.hash页面不重载,描点变化触发事件

了解vue-router原理中更新URL但不重载页面

原理之一location.hash

1.存在形式及意义

一般情况下为URL后 “#” 及其后面一部分组成,如https://www.test.com/#/something,

其中https://www.test.com为真实的路径,而#/something则为网页中的位置,称之为锚点

在访问锚点时会自动跳刀锚点所在的网页位置,通常有两种方式作为锚点

<a name=”something”></a>

<element id=”something”></element>

以上两种均可通过https://www.test.com/#/something使页面滚动到该元素的位置

2.hash的读写

location.hash可读可写的

[javascript] view plain copy

//当前URL为https://www.test.com/#/something

location.hash;              //输出 #/something

 

location.hash = ‘#/test1’;  //https://www.test.com/#/test1,并且会新增一条历史记录

在对hash写时有个需要注意的地方,如下所示

[javascript] view plain copy

//当前URL为https://www.test.com/

location.hash = “#/test”    //https://www.test.com/#/test

locationl.hash = “/#/test”  //https://www.test.com/#/#/test

当写入第一个字符不为为 “#” 时会自动生成一个 “#” 在字符串之前,再把字符串追加到生成的#后面

这样会造成有两个#,此时location.hash输出 “#/#/test”

3.onhashchange事件

在hash值发生变化时会触发该事件

[javascript] view plain copy

window.onhashchange = function(e){  

    console.log(e);  

}  

总结:

location.hash与HTML5 history类似,都能够在改变页面的URL而不会引起浏览器的重载

但是location.hash支持比较早的浏览器,而history是在HTML5的新API,可能某些较早的浏览器不支持

因此在vue-router中对此做了两种模式,即history模式与hash模式可以适应不同的浏览器

具体解释之后更新vue-router的原理分析

(文章今日已有 1 人访问,总访问量 4 ::>_<::)
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇