如何将 class smoothscroll 添加到 jquery 中定义的 link

how to add class smoothscroll to a link defined in jquery

我有一个向下按钮 div,我想添加 smoothScroll class,以便在单击它时,在跳转到 link 之前进行平滑滚动在 JS 文件中附加到它。我只是不确定如何在 window.location 之前制作 addClass 运行 每次我尝试它时它都会中断。

HTML:

<div id="downButton">
    <i class="fa fa-angle-down"></i>
  </div>

JS:

  $(function() {
  // This will select everything with the class smoothScroll
  // This should prevent problems with carousel, scrollspy, etc...
    $('.smoothScroll').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) {
          $('html,body').animate({
            scrollTop: target.offset().top
          }, 1000); // The number here represents the speed of the scroll in milliseconds
          return false;
        }
      }
    });
  });
  });

 $('#downButton').click(function () {
    window.location = '#aboutSection';
 }); 

使这项工作快速进行的最简单方法如下:

$(function(){
    $('#downButton').click(function () {
        var target = $('#aboutSection');
        $('html,body').animate({
                scrollTop: target.offset().top
              }, 1000);
     }); 
});

如果你想让它更易于重用,我会这样做:

HTML:

<div id="downButton" class="scrollme" data-goto="#aboutSection">
    <i class="fa fa-angle-down"></i>
</div>

那么 javascript 将是:

$(function() {
  $('.scrollme').click(function(){
      scrollme(this);
  });
});

function scrollme(el){
    var id = $(el).data('target');
    var $target = $('#' + id);
    console.log($target.length)
    $('html,body').animate({
        scrollTop: $target.offset().top
    }, 1000);
}

然后你只需要添加一个 class scrollme 到任何具有 data-target 属性和要滚动到的元素的 id 的元素。