Javascript &引用;window.location.hash=location.hash“;不适用于Webkit(Safari和Chrome)

Javascript &引用;window.location.hash=location.hash“;不适用于Webkit(Safari和Chrome),javascript,google-chrome,safari,webkit,Javascript,Google Chrome,Safari,Webkit,我无法在Safari中使用window.location.hash=location.hash 我正在使用javascript将我的页面内容包装成一个可滚动的DIV,放在我的网页导航栏下面。因为当javascript运行时滚动条的位置被重置,所以我丢失了URL设置的原始哈希位置。我需要在不使用javascript重新加载页面的情况下重新提示哈希位置,因此我使用的是window.location.hash=location.hash。它适用于IE8、Firefox和Opera,但不适用于Safar

我无法在Safari中使用
window.location.hash=location.hash

我正在使用javascript将我的页面内容包装成一个可滚动的DIV,放在我的网页导航栏下面。因为当javascript运行时滚动条的位置被重置,所以我丢失了URL设置的原始哈希位置。我需要在不使用javascript重新加载页面的情况下重新提示哈希位置,因此我使用的是
window.location.hash=location.hash
。它适用于IE8、Firefox和Opera,但不适用于Safari。(我也假设是Chrome,但我没有检查)。有什么建议吗


提示:我喜欢jQuery。

首先将location.hash设置为其他值,然后立即将其设置回原来的值

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

在JavaScript更改原始哈希位置之前,使用

var st = $(window).scrollTop().
如果要恢复滚动位置,请使用

$(window).scrollTop(st);

Webkit有两个异常,它们阻止
window.location.hash=location.hash
正常工作

  • Webkit响应的是
    window.location.href
    ,而不是
    window.location.hash
    (与所有其他浏览器一样)。奇怪的是,
    webkit
    仍然可以使用
    location.hash来读取URL的
    hash
    标记
  • Webkit有一个记录在案的错误,在浏览器转到新位置之前,必须将href
    位置设置为同一位置两次。错误报告
  • 这段代码解决了我的问题:(使用jQuery)

    我最终得到了

    window.location.hash = "";
    window.location.hash = "myanchor";
    
    这在我在iOS和Android chrome上测试的所有桌面浏览器中都运行良好

    go_hash('#home')
    
    功能


    请定义“不工作”。@Tomalak据我所知,这行代码在Safari中从未执行过。(1) 执行包装器javascript,将滚动条位置重置为页面顶部。(2) 此时会出现一个警报,告诉我下一步要在页面上运行的是
    窗口…hash
    函数。。。就这样。没有其他(相关的)事情发生。没有雪茄。您的代码只修改了URL哈希标记。它从未移动过页面。
    var st=$(窗口)。scrollTop()
    甚至没有在Safari中设置变量。当我运行
    $(window).scrollTop(st)
    时,控制台会给我一个变量未定义错误。(不过,该代码可以在其他浏览器中使用。)
    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
    }