如何将类smoothscroll添加到jquery中定义的链接

时间:2015-10-02 19:52:10

标签: javascript jquery scroll addclass smooth

我有一个向下按钮div,我希望添加smoothScroll类,以便在单击它时,平滑滚动在它跳转到JS文件中附加到它的链接之前发生。我只是不确定如何在window.location之前运行addClass,每次我尝试它都会中断。

HTML:

  $(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';
 }); 

JS:

plot(dist ~speed, data = cars, pch = 16); 
abline(coef(cars))

1 个答案:

答案 0 :(得分:1)

快速完成这项工作的最简单方法是:

$(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);
}

然后你只需要向一个带有data-target属性的元素添加一个scrollme类,其中id为要滚动的元素。