路由模块router实现step1

hashchange事件

需要解决的问题:
1.IE6/7及兼容模式下的IE8不支持onhashchange事件,(而且hash改变不会产生history)
    解决办法:用定时器来检测hash的变化;用隐藏的iframe调用document.write方法来产生历史;
2.hash的提取有兼容性问题:
   * IE6会取少一总分hash,
     如http://www.cnblogs.com/rubylouvre#stream/xxxxx?lang=zh_c
     IE6 > location.hash = #stream/xxxxx
     其他浏览器 > location.hash = #stream/xxxxx?lang=zh_c
   * firefox会对hash进行decodeURIComponent
     比如 http://www.cnblogs.com/rubylouvre/#!/home/q={%22thedate%22:%2220121010~20121010%22}
     firefox 15 => #!/home/q={"thedate":"20121010~20121010"}
     其他浏览器 => #!/home/q={%22thedate%22:%2220121010~20121010%22}
 
3.html5 history api 兼容pushState与replaceState, 研究一下history.js
 
 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title></title>
</head>
<body>
<a href="#a">a</a>
<a href="#b">b</a>
<a href="#c">c</a>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js"></script>
<script>
(function(global, $) {
var hashchange = 'hashchange', doc = document, documentMode = doc.documentMode,
supportHashChange = ('on' + hashchange in window) && (documentMode === void 0 || documentMode > 7); var hash = '#', last_hash = getHash(), history_hash, timeoutID, delay = 50, iframe; function getHash(url) {
url = url || doc.location.href;
return '#' + url.replace(/^[^#]*#?(.*)$/, '$1');
} //为了产生历史
function setHistory(curHash, history_hash) {
var d = iframe.document;
if (curHash != history_hash) {
d.open();
d.write('<DOCTYPE html><html><body>' + curHash + '</body></html>');
d.close();
}
} function setup() {
if (!supportHashChange) {//IE6.7及混杂模式下的IE8,不支持onhashchange事件,所以采用iframe+定时器模拟
if (!iframe) {
var $el = $('<iframe tabindex="-1" width="0" height="0" style="display:none" title="empty"></iframe>');
$el.appendTo(doc.body);
iframe = $el[0].contentWindow;
$el.on('load', function() {
$el.off('load');
var d = iframe.document;
d.open();
d.write('<DOCTYPE html><html><body>' + hash + '</body></html>');
d.close();
timeoutID = setInterval(poll, delay);
});
}
function poll() {
hash = getHash();
history_hash = iframe.document.body.innerText;
if (hash != last_hash) {//当前窗口的hash改变
//console.log('current hash:' + hash + ',last hash:' + last_hash);
setHistory(last_hash = hash, history_hash);
//todo 在这里fire hashchange事件
} else if (history_hash != hash) {//如果按下回退健或前进健
//console.log('history hash:' + history_hash + ',current hash:' + hash)
location.href = location.href.replace(/#.*/, '') + history_hash;
}
}
}
}
setup();
})(window, $);
</script>
</body>
</html>
上一篇:最近学习linux常用命令。


下一篇:GlideDemo【Glide3.7.0版本的简单使用以及圆角功能】