【问题标题】:Get back to top of page with a smooth scrolling and anchor name into URL通过平滑滚动返回页面顶部并将名称锚定到 URL
【发布时间】:2016-01-27 15:15:11
【问题描述】:

我使用this link 中的以下代码来获得平滑的滚动页面和一个回调,一旦滚动完成,就会出现锚点的名称(我正在调用 .animate 的回调):

$(function() {
    $('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; // 'this' will not be in scope in callback
      $('html,body').animate({ scrollTop: target.offset().top - 55}, 300, function() {
        location.hash = hash;
        }); 
      return false;
      }   
      }   
      }); 

    //Executed on page load with URL containing an anchor tag.
    if($(location.href.split("#")[1])) {
    var target = $('#'+location.href.split("#")[1]);
    if (target.length) {
      var hash = this.hash; // 'this' will not be in scope in callback
    $('html,body').animate({ scrollTop: target.offset().top - 55}, 300, function() {
      location.hash = hash;
      }); 
    return false;
}
}
});

我的问题是当我点击浏览器的后退按钮时,我不知道如何能够返回到页面顶部,即返回到以前的状态。例如,首先我在一个页面上(http://example.com/index.html),然后我点击一个锚点,我向下滚动到锚点,然后将锚点名称设置为 URL(http://example.com/index.htm#anchor)。但是如果我点击浏览器的后退按钮,我想被重定向到页面顶部。目前,使用上面的脚本,什么都没有发生。

更新

按照 Matthew Lymer 的回答,我通过添加进行了测试:

$(document).ready(function(event) {
      var target = window.location.href.split("#")[1];
      if (target.length) {
        var hash = this.hash; // 'this' will not be in scope in callback
      $('html,body').animate({ scrollTop: target.offset().top}, 300, function() {
        location.hash = hash;
        });
      return false;
      }

但是滚动到页面顶部的动画(当我按下返回按钮时需要)不起作用。

控制台打印:

  Type Error: target is undefined

【问题讨论】:

  • 按钮的 HTML 是什么?
  • 这个按钮是我浏览器的后退按钮
  • 看看popstate这个函数,它在URL改变时执行。 Link

标签: javascript jquery scroll


【解决方案1】:

只需重用您的函数,而不是 onclick,而是在文档准备好时触发它;

$(document).ready(function(){
    ... 
});

不要将 target 的值设置为 $(this).hash,而是使用 URL 的哈希部分

target = window.location.href.split("#");
target = target[1];

【讨论】:

  • 谢谢,能否给个代码sn-p,我不是jquery专家
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-22
  • 1970-01-01
  • 1970-01-01
  • 2018-12-25
相关资源
最近更新 更多