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

前端 未结 8 1076
死守一世寂寞
死守一世寂寞 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 :)

提交回复
热议问题