HTML onhaschange 事件
当前URL的锚定部分(以“#”符号开头)发生更改时,onhashchange属性将触发。
实例
<!DOCTYPE html>
<html>
<body onhashchange="myFunction()">
<p>点击按钮将当前网址的锚点跳转到 #part5</p>
<button onclick="changePart()">试一下</button>
<p id="demo"></p>
<script>
function changePart() {
location.hash = "part5";
var x = "The anchor part is now: " + location.hash;
document.getElementById("demo").innerHTML = x;
}
function myFunction() {
alert("The anchor part has changed!");
}
</script>
</body>
</html>
浏览器支持
事件 | |||||
---|---|---|---|---|---|
onhaschange | Yes | Yes | Yes | Yes | 15 |
定义和用法
当前URL的锚定部分(以“#”符号开头)发生更改时,onhashchange属性将触发。
锚定部分实际上是什么的一个例子:假设当前URL是
http://www.example.com/test.htm#part2 -此URL的锚定部分将是第2部分。
要调用此事件,可以:
通过设置location对象的location.hash或location.href属性来更改锚定部分
使用其他书签导航到当前页面(使用“后退”或“前进”按钮)
语法
<element onhaschange="script">
属性值
值 | 描述 |
---|---|
script | onhaschange 发生时运行的脚本。 |