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);
});
TOP