返回页面顶部,将平滑的滚动和锚名称放入网址

时间:2016-01-27 15:15:12

标签: javascript jquery scroll

我使用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

1 个答案:

答案 0 :(得分:0)

只需重复使用您的功能,但不是onclick,只需在文档准备就绪时触发它;

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

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

获取URL的哈希部分
target = window.location.href.split("#");
target = target[1];