在网址

时间:2015-11-03 22:40:16

标签: javascript anchor smooth-scrolling

我尝试在我的网站上使用Smooth Scroll,但我需要在URL上使用锚点ID,以提供浏览器Back Button的功能。问题是:我需要#anchor在400毫秒之前显示,但我不知道如何在我的脚本中调用该变量。

$(document).ready(function(){
  $('a[href*=#]').click(function() {
    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 targetOffset = $target.offset().left;
        $('html,body')
        .animate({scrollLeft: targetOffset}, 400);
 var timer = setTimeout(function() {  
        window.location.href = '#[anchor]';
   }, 400);
       return false;
      }
    }
  });
});

window.location.href = '#[anchor]';更改网址但不更改网址名称。我怎么能改变它?

1 个答案:

答案 0 :(得分:0)

锚点存储在hash变量中,请参阅示例并查看注释:

if (target.length) {

    var _this = this; // first save the reference to 'this'

    var targetOffset = $target.offset().left;
    $('html,body').animate({scrollLeft: targetOffset}, 400);
    var timer = setTimeout(function() {  
        window.location.href = _this.hash; // '_this.hash' contains the anchor
    }, 400);
    return false;

你也可以像这样使用window.location.hash

window.location.hash = _this.hash;
相关问题