发布
社区首页 >问答首页 >在火狐上使用popState平滑滚动并返回按钮-需要点击两次

在火狐上使用popState平滑滚动并返回按钮-需要点击两次
EN

Stack Overflow用户
提问于 2016-01-29 14:27:13
回答 1查看 1.5K关注 0票数 5

我试图实现一个小代码,当我点击锚(锚名称出现在动画后)时,我可以顺利滚动,如果我按下浏览器的后退按钮并更新URL (没有#锚名),我想返回到页面的顶部。

下面是代码:

代码语言:javascript
代码运行次数:0
复制
$(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的情况并非如此:一旦顺利地向下滚动,我需要在页面顶部单击“后退”按钮两次才能被重定向。

我见过this other question on stackoverflow,并且尝试使用和不使用event.preventDefault,并且只使用:

代码语言:javascript
代码运行次数:0
复制
$('html').animate

$('body').animate

但行为是一样的。

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

谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-02-06 22:28:11

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

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

在单击处理程序中,

代码语言:javascript
代码运行次数:0
复制
   $('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处理程序中,我删除了页面重新加载,但如果愿意,可以保留它:

代码语言:javascript
代码运行次数:0
复制
if (state) {
  $('html,body').animate({ scrollTop: 0 }, 300)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35086895

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档