监听fragment 的变化是这类编程的核心。在主流的浏览器(IE firefox)里面 都有一个 onhashchange 的事件监听 fragment 的变化。
但是,他们的行为有些差异。在IE8 以前的 IE版本里面,当 window.location 对象迅速变化的情况下,onhashchange 不会触发,非常奇怪的bug。
下面我写的 onhashchange 事件 没有浏览器的差异。并且加入了一个功能,页面初始化的时候,如果 url 中 有 fragment ,也触发一下
onhashchange 事件。
实现代码如下:
function addFragmentChangeEvent(callback)
{
var source = document.URL;
var url = source.split("#")[0];
if (window.location.hash)
{
var base_hash = "#____base____hash____";//改变hash,使得页面初始化的时候触发一下事件函数。
window.location = url + base_hash;
}
var prevHash = window.location.hash;
window.setInterval(
function()
{
if (window.location.hash != prevHash)
{
prevHash = window.location.hash;
callback(prevHash);
}
}, 100);
if (window.location.hash)
{
window.location = source;
}
}
其实这个技巧是js 中间常用的技巧,模拟一个事件的作用。
以上就是【监控 url fragment变化的js代码】的全部内容了,欢迎留言评论进行交流!