window.location.hash 属性使用说明

发布时间:2026-09-28 19:19:01 浏览次数:2

当浏览器地址栏中的URL中包含hash值(即以#开头的字符串),浏览器会自动将hash值存储到window.location.hash属性中。这个属性提供了一种用于操作hash值的方式,允许我们通过JavaScript动态地更改hash值,使得页面可以根据hash值的不同来展示不同的内容。

1. 获取当前页面的hash值

可以通过window.location.hash来获取当前浏览器地址栏中的hash值。例如,如果当前页面的URL为:https://example.com/#foo,则window.location.hash将为"#foo"。

console.log(window.location.hash); // "#foo"

2. 更改页面的hash值

可以通过window.location.hash属性来更改页面的hash值。例如,我们可以通过以下方式将当前页面的hash值修改为"#bar":

window.location.hash = "#bar";

当hash值被修改后,浏览器地址栏中的URL也会相应地改变。例如,当前页面的URL为https://example.com/#foo,当我们执行window.location.hash = "#bar"后,浏览器的URL将变为https://example.com/#bar。

注意:在更改hash值时,如果只是想在不刷新页面的情况下更改hash值,可以使用window.history.pushState()方法。这个方法可以将新的hash值添加到浏览器历史记录中,同时更新window.location.hash属性。

window.history.pushState(null, null, "#bar");
需要做网站?需要网络推广?欢迎咨询客户经理 13272073477