JavaScript location.hash 属性
Location 对象的 hash 属性用于设置或取得 URL 中的锚部分(包括 # 标记),语法如下:
location.hash = anchor_name
location.hash 实例
例子 1
该例子通过 location.hash 属性得到 URL 中的锚:
假设当前页面的 URL 是:http://www.5idev.com/p-javascript_history.shtml#back
<script type="text/javascript"> document.write(location.hash); </script>
运行该例子,输出:
#back
例子 2
该例子通过 location.hash 属性来设置好 URL 中的锚:
假设当前页面的 URL 是:http://www.5idev.com/test.shtml
<html>
<script type="text/javascript">
function setArchor(){
location.hash = "go";
}
</script>
<body>
<button onclick="setArchor()">设定锚链接</button>
<div style="height:800px;"></div>
<a name="go">设定的锚点</a>
<div style="height:800px;"></div>
</body>
</html>
运行该例子,点击 设定锚点链接 按钮,浏览器地址栏的 URL 将变为:http://www.5idev.com/test.shtml#go,而页面也将跳转到 go 这个锚链接部分。
提示:如果原来的 URL 中有锚链接,则原来的锚链接将被替换成新设定的锚链接。
