博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
hashchange
阅读量:7121 次
发布时间:2019-06-28

本文共 1460 字,大约阅读时间需要 4 分钟。

hashchange事件会在页面URL中的片段标识符(第一个#号开始到末尾的所有字符,包括#号)发生改变时触发.

通用信息

规范
接口
HashChangeEvent
是否冒泡
能否取消默认行为
不能
目标
defaultView
默认行为

属性

 

Property Type Description
targetRead only The browsing context (<code>window</code>).
typeRead only The type of event.
canBubbleRead only boolean Does the event normally bubble?
cancelableRead only boolean Is it possible to cancel the event?
oldURL string The previous URL from which the window was navigated. Read only
newURL string The new URL to which the window is navigating. Read only

 

浏览器兼容性

 

  • Desktop  
  • Mobile
Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support 5.0 3.6 (1.9.2)
Support for the oldURL/newURL attributes added in Firefox 6.
8.0 10.6 5.0

 

里有几个用JavaScript模拟该事件的脚本,原理基本上都是隔一段时间检测一下location.hash是否发生变化.下面的这个实现可以在<code>window.onhashchange</code>属性上绑定事件处理函数:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
(
function
(window) {
 
  
// 如果浏览器原生支持该事件,则退出 
if
(
"onhashchange"
in
window.document.body ) {
return
; }
 
  
var
location = window.location,
    
oldURL = location.href,
    
oldHash = location.hash;
 
  
// 每隔100ms检测一下location.hash是否发生变化
  
setInterval(
function
() {
    
var
newURL = location.href,
      
newHash = location.hash;
 
    
// 如果hash发生了变化,且绑定了处理函数...
    
if
( newHash != oldHash &&
typeof
window.onhashchange ===
"function"
) {
      
// execute the handler
      
window.onhashchange({
        
type:
"hashchange"
,
        
oldURL: oldURL,
        
newURL: newURL
      
});
 
      
oldURL = newURL;
      
oldHash = newHash;
    
}
  
}, 100);
 
})(window);

相关事件

转载地址:http://dpxel.baihongyu.com/

你可能感兴趣的文章
数据类型转换
查看>>
Vim简明教程
查看>>
C/C++程序调试和内存检测
查看>>
vlan 03
查看>>
从零撸起-微信小游戏-1,最基础的知识
查看>>
将Bitmap对象转化为图片文件File
查看>>
DEV报表注意事项(二)
查看>>
超实用的Linux/Unix快捷键大汇总
查看>>
流编辑器sed命令详解
查看>>
wps for linux 不能使用搜狗输入法
查看>>
PHP与MySQL学习笔记9:创建Web数据库
查看>>
useradd、adduser和userdel在使用时的注意事项
查看>>
替你写代码
查看>>
xmake v2.0.3 更新
查看>>
注释 005
查看>>
002 about print
查看>>
提高Web页面性能的技巧
查看>>
11月份中国服务器市场:IBM以36.8%领跑市场
查看>>
Java实现Zip压缩解压缩
查看>>
4月第2周全球域名商TOP15:中国占据2个席位
查看>>