How to add smooth scrolling to Bootstrap's scroll spy function

前端 未结 8 1018
死守一世寂寞
死守一世寂寞 2020-11-30 17:30

I\'ve been trying to add a smooth scrolling function to my site for a while now but can\'t seem to get it to work.

Here is my HTML code relating to my navigation:<

相关标签:
8条回答
  • 2020-11-30 18:07

    I combined it, and this is the results -

    $(document).ready(function() {
         $("#toTop").hide();
    
                // fade in & out
           $(window).scroll(function () {
                        if ($(this).scrollTop() > 400) {
                            $('#toTop').fadeIn();
                        } else {
                            $('#toTop').fadeOut();
                        }
                    });     
      $('a[href*=#]').each(function() {
        if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
        && location.hostname == this.hostname
        && this.hash.replace(/#/,'') ) {
          var $targetId = $(this.hash), $targetAnchor = $('[name=' + this.hash.slice(1) +']');
          var $target = $targetId.length ? $targetId : $targetAnchor.length ? $targetAnchor : false;
           if ($target) {
             var targetOffset = $target.offset().top;
             $(this).click(function() {
               $('html, body').animate({scrollTop: targetOffset}, 400);
               return false;
             });
          }
        }
      });
    });
    

    I tested it and it works fine. hope this will help someone :)

    0 讨论(0)
  • 2020-11-30 18:08

    What onetrickpony posted is okay, but if you want to have a more general solution, you can just use the code below.

    Instead of selecting just the id of the anchor, you can make it bit more standard-like and just selecting the attribute name of the <a>-Tag. This will save you from writing an extra id tag. Just add the smoothscroll class to the navbar element.

    What changed

    1) $('#nav ul li a[href^="#"]') to $('#nav.smoothscroll ul li a[href^="#"]')

    2) $(this.hash) to $('a[name="' + this.hash.replace('#', '') + '"]')

    Final Code

    /* Enable smooth scrolling on all links with anchors */
    $('#nav.smoothscroll ul li a[href^="#"]').on('click', function(e) {
    
      // prevent default anchor click behavior
      e.preventDefault();
    
      // store hash
      var hash = this.hash;
    
      // animate
      $('html, body').animate({
        scrollTop: $('a[name="' + this.hash.replace('#', '') + '"]').offset().top
      }, 300, function(){
    
        // when done, add hash to url
        // (default click behaviour)
        window.location.hash = hash;
    
      });
    });
    
    0 讨论(0)
提交回复
热议问题