在URL上使用锚点进行平滑滚动

Smooth Scroll with Anchor on URL

本文关键字:平滑 滚动 URL      更新时间:2023-09-26

我试图在我的网站上使用平滑滚动,但我需要URL上的锚id,以提供浏览器返回按钮的功能。问题是:我需要#anchor在400ms之前出现,但我不知道如何在脚本中调用该变量。

$(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]';会更改url,但不会更改锚点名称。我该怎么改?

锚点存储在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;