平滑滚动并使用 Firefox 上的 popState 返回按钮 - 需要单击两次

smooth scrolling and get back button with popState on Firefox - need to click twice

本文关键字:单击 两次 按钮 滚动 Firefox 返回 popState 上的 平滑      更新时间:2023-09-26

我正在尝试实现一个小代码,当我单击锚点时,我可以使用它获得平滑滚动(并且动画后会出现锚点名称),如果我按下浏览器的后退按钮并更新 URL(没有 #anchor 名称),我想返回页面顶部。

这是代码:

$(function() {
  // Smooth scrolling when clicking on anchor
  $('a[href*=#]:not([href=#])').click(function(event) {
    event.preventDefault();
    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) {
        var hash = this.hash; 
        $('html,body').animate({ scrollTop: target.offset().top - 55}, 300, function() {
          location.hash = hash;
          href = window.location.href;
          history.pushState({page:href}, null, href);
        });
        return false;
      }
    }
  });
  // Get smooth scrolling to the top whith back button of browser
  $(window).bind('popstate', function(event) {
    var state = event.originalEvent.state;
    var target = window.location.href.split('#');
    var href = target[0];
    if (state) {
      $('html,body').animate({ scrollTop: 0 }, 300, function() {
        window.location.href = href;
     })
   }
  });
  // First page loading
  window.onload = function() {
    history.replaceState({ path: window.location.href }, '');
  }
});

上述所有功能在Safari和Chrome下都能很好地运行。但 Firefox 的情况并非如此:一旦执行平滑向下滚动,我需要在返回按钮上单击两次以重定向到页面顶部。

我已经在stackoverflow上看到了另一个问题,并尝试使用和不使用event.preventDefault,也只输入:

$('html').animate

$('body').animate

但行为是一样的。

如果有人能看到为什么它不起作用。

谢谢

您正在触发此行中的其他历史记录更改location.hash = hash;

所以,我对你的代码做了一些更改,它现在可以在我的FF中工作。

在点击处理程序中,

   $('html').animate({ scrollTop: target.offset().top - 55}, 300, function() {
      href = window.location.href;
      history.pushState({page:href}, null, href.split('#')[0]+hash);
    });

此外,似乎$('html,body').animate运行两次回调,因此弄乱了历史。这就是为什么我只留下html。

在popstate处理程序中,我删除了页面重新加载,但是如果您愿意,可以保留它:

if (state) {
  $('html,body').animate({ scrollTop: 0 }, 300)