【问题标题】:Chrome ignoring hashes in URLChrome 忽略 URL 中的哈希值
【发布时间】:2016-03-04 21:29:48
【问题描述】:

我花了很长时间试图找到这个问题的答案,但没有任何成功。基本上,当他们转到healthdollars.com/#contact 时,我需要将用户滚动到网站的联系人部分。这在 Safari 中运行良好,但在 Chrome 中我没有任何运气。我尝试过使用 jQuery/Javascript 来强制浏览器向下滚动,但我无法做到。

有人有什么想法吗?这让我发疯 - 尤其是因为这是一件如此简单的事情。

【问题讨论】:

  • 当我点击你的链接时,它在 chrome 中对我有用

标签: javascript html google-chrome url


【解决方案1】:

不是完整的答案,但在 Chrome 中,如果您禁用 Javascript,我相信您会得到所需的行为。这让我相信你的 JavaScript 中的某些东西正在阻止默认浏览器行为。

【讨论】:

  • 事实证明这是 Modernizr 正在做的事情。一旦我删除它,事情又开始工作了。
【解决方案2】:

在我看来,当页面首次加载时目标元素不存在。如果我导航到页面然后添加哈希,我没有任何问题。

if (window.location.hash.length && $(location.hash)) {
  window.scrollTo(0, $(location.hash).offset().top)
}

检查哈希,找到元素的页面偏移量,然后滚动到那里 (x, y)。

edit:我注意到,事实上,页面从#contact 开始,然后滚动回顶部。我同意其他回答者的观点,即您的页面上有一些内容将您滚动到顶部。我会在添加 hack 之前搜索它。

【讨论】:

    【解决方案3】:

    你可以用 JS 来做到这一点,例如`如果你有 JQuery。

    $(function(){
      // get the selector to scroll (#contact)
      var $to = $(window.location.hash);
    
      // jquery animate
      $('html'/* or body */).animate({ scrollTop: $to.offset().top });
    });
    

    【讨论】:

      【解决方案4】:

      HTML 5 中不存在 name 属性,因此当您使用 DOCTYPE html 时,chrome 看起来已经过时了 name 属性。

      其他浏览器还没有赶上。

      改变

      <a name="contact"></a>
      

      <a id="contact"></a>
      

      【讨论】:

        【解决方案5】:

        也许这个使用 vanilla javascript 的解决方法可能有用:

        // Get the HTMLElement that you want to scroll to. 
        var element = document.querySelector('#contact');
        // Stories the height of element in the page.
        var elementHeight = element.scrollHeight;
        // Get the HTMLElement that will fire the scroll on{event}.
        var trigger = document.querySelector('[href="#contact"]');    
        trigger.addEventListener('click', function (event) {
          // Hide the hash from URL.
          event.preventDefault();
          // Call the scrollTo(width, height) method of window, for example.
          window.scrollTo(0, elementHeight);
        })
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-01-02
          • 2017-08-23
          • 2021-11-19
          • 2020-12-05
          • 2013-01-16
          • 2017-12-22
          • 2016-01-10
          • 2012-05-19
          相关资源
          最近更新 更多