小编典典

jQuery平滑滚动到锚点?

javascript

有没有一种方法可以使用jQuery向下滚动到锚链接?

喜欢:

$(document).ready(function(){
  $("#gotomyanchor").click(function(){
      $.scrollSmoothTo($("#myanchor"));
  });
});


阅读 337

收藏
2020-05-01

共1个答案

小编典典

这是我的方法:

    var hashTagActive = "";
    $(".scroll").on("click touchstart" , function (event) {
        if(hashTagActive != this.hash) { //this will prevent if the user click several times the same link to freeze the scroll.
            event.preventDefault();
            //calculate destination place
            var dest = 0;
            if ($(this.hash).offset().top > $(document).height() - $(window).height()) {
                dest = $(document).height() - $(window).height();
            } else {
                dest = $(this.hash).offset().top;
            }
            //go to destination
            $('html,body').animate({
                scrollTop: dest
            }, 2000, 'swing');
            hashTagActive = this.hash;
        }
    });

然后,您只需要像这样创建锚:

<a class="scroll" href="#destination1">Destination 1</a>
2020-05-01