使用 # 时,Chrome浏览器中的锚点<a>标签无法正常工作

36

这是我在网页上使用的代码,

<li><a href="/explore/#Sound">Sound</a></li>

(出现在所有页面上的菜单中)

<a id="Sound"><a>

我想在页面上添加链接,但只有在Chrome浏览器中,当我想要滚动到标签时,标签上的内容才能显示。但这些锚点适用于IE和Firefox浏览器。有什么建议吗?


请问您有该页面的链接吗? - AshboDev
https://dev.phonaudio.com/explore/#Sound - Jake_
需要进行身份验证。你能在 JSFiddle 上做吗? - AshboDev
哦,当然我的错,是的我会。 - Jake_
虽然在jsfiddle中它无法正常工作,因为问题出现在我从另一个页面转到这个页面时,如果我已经在该页面上,则#起作用。 - Jake_
显示剩余7条评论
11个回答

57

结果表明这是一些版本的Chrome中的错误,为需要的任何人发布解决方法!:)

$(document).ready(function () {
        var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
        if (window.location.hash && isChrome) {
            setTimeout(function () {
                var hash = window.location.hash;
                window.location.hash = "";
                window.location.hash = hash;
            }, 300);
        }
    });

1
完全没有问题!通常一个排除的过程会让你得到答案! - AshboDev
1
感谢@Jake_告诉我们这个bug... :) - Praveen Kumar Purushothaman
在Google Tag Manager中也能很好地工作。 - Sirius_B
各位,我应该编辑并添加这段代码到我的WordPress网站的哪个文件中呢?我的锚点链接在首页上。我应该将该代码添加到首页的HTML中吗? - C. Kontos
2
这将影响浏览器的历史记录。我使用了 window.location.replace(hash) 解决了这个问题。 - dariush
显示剩余5条评论

36

我尝试了之前发布的解决方法,但对我无效。经过几天的搜索,我终于找到了一个完美的解决方案,所以觉得值得分享:

 $(function() {
       $('a[href*="#"]:not([href="#"])').click(function() {
         if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
           var target = $(this.hash);
           target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
           if (target.length) {
             $('html, body').animate({
               scrollTop: target.offset().top
             }, 1000);
             return false;
           }
         }
       });
     });

被接受的答案对我没用,但这个答案有效。谢谢。 - Luu Hoang Bac
这应该是被接受的答案。同时修复Safari iOSX和Mac OSX上的相同问题。 - Lelio Faieta

6

如果你像我一样从外部网站找到 SPA 网站的锚点链接无法工作。是的,浏览器加载页面的速度太快了,它在加载页面时找不到你的锚点。

为了解决这个问题,在你的 SPA 生命周期中(React 中的 useEffect 和 Vue 中的 mounted),添加一些代码来检查 URL 锚点并自己滚动到相应位置。

以下是使用 React 的示例:

  useEffect(()=> {
    if(document.location.hash === '#some-anchor') {
      setTimeout(()=> {
          document
            .querySelector("#some-anchor")
            .scrollIntoView({ behavior: "smooth", block: "start" })
      }, 300)
    }
  }, [])

我们想知道我们的AEM 6.5实例是否表现相同。我们突然无法使用带有锚点的URL。 - linnse

4

我也遇到了这个问题(使用链接进行同一页导航),解决方案非常简单(虽然让人沮丧难以想出)。希望这可以帮助你 - 我还检查了IE,Firefox和Chrome,它可以跨浏览器正常工作(截至2019年5月22日)。

你的链接应该像这样:

<a href="pagename.html##anchorname">Word as link you want people to click</a>

你的锚点应该长成这样:

<a name="#anchorname">Spot you want to appear at top of page once link is clicked</a>

我的天啊,我花了一整天的时间寻找解决方案,谢谢你! - Daria M
无法使其工作 - Slion

1
这个答案是为了帮助遇到同样问题但脚本无效的人而准备的。尝试从页面上的所有图像中移除loading='lazy'decoding='async',或者为它们设置widthheight属性。对我来说,这方法非常有效。

移除懒加载解决了这个问题,谢谢! - Majali

1
尝试使用: 对于菜单页面
<li><a href="/explore/##Sound">Sound</a></li>

在所有页面上出现的菜单
<a id="#Sound"><a>

这在所有版本的Chrome浏览器中都可以很好地工作!
我已经在我的浏览器上测试过了。


0

不确定这是否有所帮助,但我意识到我的锚点在IE中可以工作,但在Firefox或Chrome中无法工作。最终我添加了##到我的锚点中,这解决了问题。

例如: a href="##policy">目的和政策声明

而不是:

a href="#policy">目的和政策声明


我尝试了这个,但当点击时锚点不再起作用。 - jbobbins

0
这是我根据@Jake_的回答修改后的版本,解决了Chrome/angular在使用ui-router进行初始页面加载时无法滚动到正确锚点的问题(原始答案会导致我的代码抛出“Transition superseeded”异常):
angular.module('myapp').run(function($transitions, $state, $document, $timeout) {
  var finishHook = $transitions.onSuccess({}, function() { // Wait for the complete routing path to settle
    $document.ready(function() { // On DOM ready - check whether we have an anchor and Chrome
      var hash;
      var params;
      var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
      finishHook(); // Deregister the hook; the problem happens only on initial load
      if ('#' in $state.params && isChrome) {
        hash = $state.params['#']; // Save the anchor
        params = _.omit($state.params, ['id', '#']);
        $timeout(function() {
          // Transition to the no-anchor state
          $state.go('.', params, { reload: false, notify: false, location: 'replace' });
          $timeout(function() {
            // Transition back to anchor again
            $state.go('.', _.assign($state.params, { '#': hash }), { reload: false, notify: false, location: 'replace' });
          }, 0);
        }, 0);
      }
    });
  }, {invokeLimit: 1});
});

0

我花了一些时间找到了适当的解决方案来解决这个问题。在我的情况下,这与浏览器版本和链接本身无关,而是由于页面在Next.js中没有完全加载。因此,加载时的水合作用还没有到达我的id,这就是为什么它不在页面上,浏览器也不知道它的存在。因此,它也无法滚动到那里。

在我这种情况下,最简单的解决方案是将id =“some-id”从section组件移动到索引页面本身,并使用div将section组件包裹起来并使用相同的id:

      <div id="some-id">
        <Video />
      </div>

它能够工作是因为页面组件在页面加载时加载,但深度嵌套的组件稍后才被注入。


-5
 <html>
   <body>
    <li>
      <a href="#Sound">Sound</a>
    </li>
    <a id="Sound" href="www.google.com">I AM CALLED</a>
   </body>
</html>

使用这段代码,它将调用ID值为"sound"的锚点标签


这是我已经有的,但由于Chrome中的一个错误而无法工作,还是谢谢 :) - Jake_

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