location.hash 属性表示 URL 中的片段标识符( 和后面的部分)。
location.hash = newHash
newHash
为新片段标识符的字符串。
获取当前 URL 片段:
const currentHash = location.hash;
console.log(currentHash); // 输出 "my-anchor"
设置新 URL 片段:
location.hash = "new-anchor";
console.log(location.hash); // 输出 "new-anchor"
使用相对路径更新片段标识符.hash 属性时会触发
hashchange
事件。
window.addEventListener("hashchange", function(e) {console.log(e.newURL);
});
href
属性包含片段标识符,则浏览器将滚动到页面中的相应元素。
location.hash
中存储状态或视图信息。
location.hash
时,请确保它对用户有意义且易于理解。
浏览器 | 支持 |
---|---|
Chrome | 是 |
Firefox | 是 |
Safari | 是 |
Edge | 是 |
Opera | 是 |
IE | 是 |
location.href
location.host
location.hostname
location.origin
location.pathname
location.port
location.Protocol
location.Search
hashchange
本文地址:https://www.qianwe.com/article/b5fe68d0274d71fa812a.html
上一篇:HTTP响应头Locationhttp响应消息的状态行由...
下一篇:利用`locationhash`获取或设置当前URL片段...