监听浏览器hash变化和html5 pullstate特性

来源:互联网 发布:万得股票mac版 编辑:程序博客网 时间:2024/05/19 15:43

最近在学vue,用到了路由,虽然之前用正美大神的avalon的时候也用到了路由,但是却没有现在这样迫切的想知道前端路由的实现原理,


触发浏览器地址管理机制的情况大致有三种:

1.a链接跳转

2.浏览器地址栏hash改变,可以直接通过js改变window.location.hash

3.使用HTML5特效 pullstate


第一个会导致当前窗口刷新,第二个和第三个不会导致刷新


使用2和3的原因:

1.window.location的其他属性的修改并不能监听

2.单页面不需要刷新

3.可以通过监听对应的事件获取上一页的地址


兼容性:

hash兼容IE8[IE7文档模型下不支持],参考文档:

http://www.runoob.com/jsref/prop-doc-documentmode.html

http://www.86y.org/art_detail.aspx?id=781


修改和监听hash变化---代码如下:

<!DOCTYPE HTML><html><head>    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">    <title>无标题文档</title>    <script>    window.onload = function() {        var oInput2 = document.getElementById('input1');        var oDiv2 = document.getElementById('div1');        oInput2.onclick = function() {            //var arr = randomNum(35,7);            var b = '恶搞';            window.location.hash = "#100";        };        if ("onhashchange" in window) {            window.onhashchange = function(ev) {                alert("b")                console.log(ev)                oDiv2.innerHTML = window.location.hash;            };        }    };    </script></head><body>    <input type="button" value="通过pushstate改变" id="input1">    <div id="div1"></div></body></html>


通过html特性触发浏览器历史队列---代码:

<!DOCTYPE HTML><html><head>    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">    <title>无标题文档</title>    <script>    window.onload = function() {        var oInput2 = document.getElementById('input1');        var oDiv2 = document.getElementById('div1');        oInput2.onclick = function() {            //var arr = randomNum(35,7);            var b = '恶搞';            window.location.hash = "#100";        };        if ("onhashchange" in window) {            window.onhashchange = function(ev) {                alert("b")                console.log(ev)                oDiv2.innerHTML = window.location.hash;            };        }    };    </script></head><body>    <input type="button" value="通过pushstate改变" id="input1">    <div id="div1"></div></body></html>



0 0
原创粉丝点击