Window location.hash

实例

获取 URL 的锚部分:

  1. <!DOCTYPE html>
  2. <html>
  3. <body>
  4. <h2>hash 属性</h2>
  5. <p><a id="ms" href="/js-version/js-es6.html#mark_array_from">JavaScript 2015 Array.from()</a><p>
  6. <p id="demo">
  7. <script>
  8. let url = document.getElementById("ms");
  9. document.getElementById("demo").innerHTML = "The anchor portion of the URL is: " + url.hash;
  10. </script>
  11. </body>
  12. </html>

设置另外一个锚:

  1. <!DOCTYPE html>
  2. <html>
  3. <body>
  4. <h2>hash 属性</h2>
  5. <p><a id="ms" href="/js-version/js-es6.html#mark_array_from">JavaScript 2015 Array.from()</a><p>
  6. <p id="demo">
  7. <script>
  8. location.hash = "mark_array_find";
  9. document.getElementById("demo").innerHTML = "The anchor part is now: " + location.hash;
  10. </script>
  11. </body>
  12. </html>

定义与用法

location.hash 属性设置或返回 URL 的锚定部分,包含 hash 符号(#)。


Note

location.hash 用来 设置 锚的时候, 不包含 hash 符号(#)。


语法

返回 hash 属性:

  1. location.hash

设置 hash 属性:

  1. location.hash = anchorname

参数

参数描述
anchornameURL 的锚部分。

返回值

类型描述
A stringURL 的锚部分,包括哈希符号(#)

浏览器支持

location.hash 所有浏览器都支持:

属性
location.hashYesYesYesYesYes

分类导航