平滑滚动页面上的所有链接和按钮

smooth scrolling for all links and buttons on a page

前 26 行让我可以平滑滚动导航栏和徽标中的所有链接,但我不知道如何将它与我从另一个教程中获得的向上滚动按钮结合使用。有没有办法让所有链接在第一段代码中滚动,而不仅仅是导航栏中的元素?

$(document).ready(function(){
  // Add scrollspy to <body>
  $('body').scrollspy({target: ".navbar", offset: 50});   

  // Add smooth scrolling on all links inside the navbar
  $("a").on('click', function(event) {
    // Make sure this.hash has a value before overriding default behavior
    if (this.hash !== "") {
      // Prevent default anchor click behavior
      event.preventDefault();

      // Store hash
      var hash = this.hash;

      // Using jQuery's animate() method to add smooth page scroll
      // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
      $('html, body').animate({
        scrollTop: $(hash).offset().top
      }, 800, function(){

        // Add hash (#) to URL when done scrolling (default click behavior)
        window.location.hash = hash;
      });
    }  // End if
  });
});

jQuery(window).scroll(function(){
  if (jQuery(this).scrollTop() > 300) {
    jQuery('.scrollToTop').fadeIn();
  } else {
    jQuery('.scrollToTop').fadeOut();
  }
});

//Click event to scroll to top

jQuery('.scrollToTop').click(function(){
  jQuery('html, body').animate({scrollTop : 0},800);
  return false;
});

您需要将导航栏link和您的scrollToToplink的点击事件分开,然后注册scrollToTop link 还有一个点击事件。所以你的代码看起来像这样(假设你在导航栏上添加 class 'nav-link' 到 links):

$(document).ready(function(){
  // Add scrollspy to <body>
  $('body').scrollspy({target: ".navbar", offset: 50});   

  $('.scrollToTop').on('click',function(event){
      event.preventDefault();
    $('html, body').animate({scrollTop : 0}, 800);

  });

  // Add smooth scrolling on all links inside the navbar
  $(".nav-link").on('click', function(event) {
    // Make sure this.hash has a value before overriding default behavior
    if (this.hash !== "") {
      // Prevent default anchor click behavior
      event.preventDefault();

      // Store hash
      var hash = this.hash;

      // Using jQuery's animate() method to add smooth page scroll
      // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
      $('html, body').animate({
        scrollTop: $(hash).offset().top
      }, 800, function(){

        // Add hash (#) to URL when done scrolling (default click behavior)
        window.location.hash = hash;
      });
    }  // End if
  });
});

jQuery(window).scroll(function(){
      if (jQuery(this).scrollTop() > 300) {
        jQuery('.scrollToTop').fadeIn();
      } else {
        jQuery('.scrollToTop').fadeOut();
      }
});