在Webkit(Safari和Chrome)中,“window.location.hash = location.hash”无法运行。

9

在Safari中,我无法让window.location.hash = location.hash起作用。

我使用JavaScript将页面内容包装在一个可滚动的DIV中,放置在网页中导航栏下方。由于当JavaScript运行时滚动条的位置会被重置,所以我失去了URL设置的原始哈希位置。我需要在JavaScript中重新获取哈希位置而不必重新加载页面,因此我使用window.location.hash = location.hash。它在IE8、Firefox和Opera中可以工作,但在Safari中却不能。(我会假设Chrome也是如此,但我还没有检查)。有什么建议吗?

提示:我喜欢jQuery。


请定义“不起作用”是什么意思。 - Lightness Races in Orbit
1
据我所知,这行代码在Safari中从未执行过。 (1)包装的JavaScript被执行,将滚动条位置重置为页面顶部。(2)弹出一个警告,告诉我window...hash函数是接下来要在页面上运行的东西......就这样。没有其他(相关)的事情发生。 - Brandon Lebedev
5个回答

12

Webkit有两个特殊的地方阻止了window.location.hash = location.hash正常工作。

  1. Webkit响应window.location.href而不是像其他所有浏览器一样响应window.location.hash。但奇怪的是,webkit仍然可以使用location.hash读取URL的hash标签。
  2. Webkit有一个已知的bug,必须将hreflocation设置为相同的位置两次,才能使浏览器跳转到新的位置。Bug报告在此处

这段代码解决了我的问题:(使用jQuery)。

$(document).ready(function() {
    gotoHASH()
};

function gotoHASH() {
    if (location.hash) {
        if ( $.browser.webkit == false ) {
            window.location.hash = location.hash;
        } else {
            window.location.href = location.hash;
        }
    }
};

10

最终我得到了

window.location.hash = "";
window.location.hash = "myanchor";

这个在我测试的所有桌面浏览器以及iOS和Android Chrome上都运行良好。


0
go_hash('#home')

该函数...
function go_hash(hash) {
  console.log('go_hash: ' + hash)
  if(hash.indexOf('#') == -1)
    hash = '#' + hash
  if(document.location.hash) {
    document.location.hash = hash
    return
  }
  if(window.location.hash) {
    window.location.hash = hash
    return
  }
  if(document.location.href) {
    document.location.href = hash
    return
  }
  window.location.href = hash
}

0

首先将location.hash设置为其他内容,然后立即将其设置回来。

var t = window.location.hash;
window.location.hash = "non-existant-id";
window.location.hash = t;

不行。你的代码只修改了URL的哈希标签,但没有移动页面。 - Brandon Lebedev

0

在 JavaScript 更改原始哈希位置之前,使用以下方法获取滚动位置:

var st = $(window).scrollTop().

当您想要恢复滚动位置时,请使用

$(window).scrollTop(st);

“var st = $(window).scrollTop()”甚至无法在Safari中设置变量。当我运行“$(window).scrollTop(st)”时,控制台会给出未定义的变量错误。(该代码在其他浏览器中可以正常运行。) - Brandon Lebedev

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接