【问题标题】:"window.location.hash = location.hash" does not work in Webkit (Safari & Chrome)“window.location.hash = location.hash”在 Webkit(Safari 和 Chrome)中不起作用
【发布时间】:2011-08-07 04:37:33
【问题描述】:

我无法让window.location.hash = location.hash 在 Safari 中工作。

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

提示:我喜欢 jQuery。

【问题讨论】:

  • 请定义“不起作用”。
  • @Tomalak 据我所知,那行代码永远不会在 Safari 中执行。 (1) 包装器 javascript 执行,将滚动条位置重置为页面顶部。 (2) 出现一个警报,告诉我window...hash 函数是页面上运行的下一个东西......就是这样。没有其他(相关的)发生。

标签: javascript google-chrome safari webkit


【解决方案1】:

Webkit 有两个奇怪的地方会阻止 window.location.hash = location.hash 正常工作。

  1. Webkit 响应window.location.href 而不是window.location.hash(就像所有其他浏览器一样)。奇怪的是,webkit 仍然可以使用location.hash 读取 URL 的 hash 标签
  2. Webkit 有一个已记录的错误,其中 href location 必须设置到同一位置两次,然后浏览器才会转到新位置。错误报告here

这段代码解决了我的问题:(使用 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;
        }
    }
};

【讨论】:

    【解决方案2】:

    我最终得到了

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

    这在我在 iOS 和 Android chrome 中测试过的所有桌面浏览器中运行良好。

    【讨论】:

      【解决方案3】:

      先将 location.hash 设置为其他值,然后立即将其设置回去。

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

      【讨论】:

      • 没有雪茄。您的代码仅修改了 URL 哈希标记。它从不移动页面。
      【解决方案4】:

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

      获取滚动位置
      var st = $(window).scrollTop().
      

      当你想恢复滚动位置时,使用

      $(window).scrollTop(st);
      

      【讨论】:

      • var st = $(window).scrollTop() 甚至没有在 Safari 中设置变量。当我运行$(window).scrollTop(st) 时,控制台给了我一个变量未定义的错误。 (不过,该代码可在其他浏览器中使用。)
      【解决方案5】:
      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
      }
      

      【讨论】:

        猜你喜欢
        • 2019-02-28
        • 1970-01-01
        • 2013-04-26
        • 1970-01-01
        • 2013-07-19
        • 2014-10-14
        • 2013-09-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多