该例子通过 location.hash 属性得到 URL 中的锚:
假设当前页面的 URL 是:http://www.520mg.com/p-javascript_history.shtml#back
<script type="text/javascript"> document.write(location.hash); </script>
运行该例子,输出:
#back
该例子通过 location.hash 属性来设置好 URL 中的锚:
假设当前页面的 URL 是:http://www.520mg.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.520mg.com/test.shtml#go,而页面也将跳转到 go 这个锚链接部分。
提示:如果原来的 URL 中有锚链接,则原来的锚链接将被替换成新设定的锚链接。