租用问题

质量为本、客户为根、勇于拼搏、务实创新

< 返回租用问题列表

window.location.hash的使用有哪些方法,window.location.hash作用

发布时间:2024-03-08 15:27:25

window.location.hash的使用有哪些方法

window.location.hash是用于获得或设置URL中的片断标识符(hash)部份的属性。片断标识符是URL中“#”符号后的部份,通经常使用于在页面内部进行导航或标识特定内容。

要获得当前URL中的片断标识符,可使用以下语法:

var hash = window.location.hash;

要设置URL中的片断标识符,可使用以下语法:

window.location.hash = "#section1";

在设置片断标识符后,页面会自动转动到具有与片断标识符匹配的id属性的元素。可以通过监听hashchange事件来检测片断标识符的变化:

window.addEventListener("hashchange", function() {
    console.log("Hash changed to: " + window.location.hash);
});