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

Javascript 使用Firefox上的popState平滑滚动和返回按钮-需要单击两次,javascript,jquery,firefox,Javascript,Jquery,Firefox,我正在尝试实现一个小代码,当我点击锚点(动画后会显示锚点名称)时,我可以用它平滑地滚动,如果我按下浏览器的后退按钮并更新URL(没有锚点名称),我想返回到页面顶部 代码如下: $(function() { // Smooth scrolling when clicking on anchor $('a[href*=#]:not([href=#])').click(function(event) { event.preventDefault(); if (location.

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

代码如下:

$(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的情况并非如此:一旦执行了平滑向下滚动,我需要单击两次后退按钮以重定向页面顶部的方向

我已经看到并尝试过使用event.preventDefault和不使用event.preventDefault,并且只使用了:

$('html').animate
或<代码>$(“身体”)。制作动画

但行为是一样的

如果有人能明白为什么它不起作用


谢谢

您正在这一行触发额外的历史记录更改
location.hash=hash

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

在click handler中

   $('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)

感谢你的回答,它对我很有效,但我想避免在返回页面顶部时重新加载页面:是否可以在不使用“window.location.href=href”的情况下修改URL(实际删除#锚定)?另一句话:如果我不使用回调到$('html,body')。动画({scrollTop:0},300),动画没有实现(平滑滚动),我直接去锚,没有平滑滚动。最后,我使用“history.pushState({},null,newUrl)”返回顶部,没有重新加载页面,thanks@user1773603我回答的最后三行是关于页面重新加载的。未删除
window.location.href=href工作?我将其替换为“history.replaceState({},null,href)”,这样就不会重新加载页面了,谢谢