簡體   English   中英

如何為 Bootstrap 的滾動間諜功能添加平滑滾動

[英]How to add smooth scrolling to Bootstrap's scroll spy function

一段時間以來,我一直在嘗試向我的網站添加平滑滾動功能,但似乎無法使其正常工作。

這是與我的導航相關的 HTML 代碼:

<div id="nav-wrapper">
<div id="nav" class="navbar navbar-inverse affix-top" data-spy="affix" data-offset-top="675">
  <div class="navbar-inner" data-spy="affix-top">
    <div class="container">

      <!-- .btn-navbar is used as the toggle for collapsed navbar content -->
      <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </a>

      <!-- Everything you want hidden at 940px or less, place within here -->
      <div class="nav-collapse collapse">
        <ul class="nav">
            <li><a href="#home">Home</a></li>
            <li><a href="#service-top">Services</a></li>
            <li><a href="#contact-arrow">Contact</a></li>
        </ul><!--/.nav-->
      </div><!--/.nav-collapse collapse pull-right-->
    </div><!--/.container-->
  </div><!--/.navbar-inner-->
</div><!--/#nav /.navbar navbar-inverse-->
</div><!--/#nav-wrapper-->

這是我添加的JS代碼:

<script src="js/jquery.scrollTo-1.4.3.1-min.js"></script>

<script>
    $(document).ready(function(e) {

        $('#nav').scrollSpy()
        $('#nav ul li a').bind('click', function(e) {
            e.preventDefault();
            target = this.hash;
            console.log(target);
            $.scrollTo(target, 1000);
        });
    });
</script>

就其價值而言, 這里是我收到有關我迄今為止所做工作的信息的地方,這里是我的網站的當前形式。 如果你能幫我,我會給你烤餡餅或餅干之類的。 謝謝!

你真的需要那個插件嗎? 您可以為scrollTop屬性設置動畫:

$("#nav 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: $(hash).offset().top
     }, 300, function(){

       // when done, add hash to url
       // (default click behaviour)
       window.location.hash = hash;
     });

});

小提琴

如果你有一個固定的導航欄,你將需要這樣的東西。

從以上最佳答案和評論中汲取...

$(".bs-js-navbar-scrollspy li a[href^='#']").on('click', function(event) {
  var target = this.hash;

  event.preventDefault();

  var navOffset = $('#navbar').height();

  return $('html, body').animate({
    scrollTop: $(this.hash).offset().top - navOffset
  }, 300, function() {
    return window.history.pushState(null, null, target);
  });
});

首先,為了防止“未定義”錯誤,在調用preventDefault()之前將散列存儲到變量target ,然后引用該存儲的值,如 pupadupa 所述。

下一個。 您不能使用window.location.hash = target因為它同時而不是單獨設置 url 和位置。 您最終將在元素的開頭找到位置,該元素的 id 與 href... 匹配,但被固定的頂部導航欄覆蓋。

為了解決這個問題,您將 scrollTop 值設置為目標的垂直滾動位置值減去固定導航欄的高度。 直接定位該值可以保持平滑滾動,而不是在之后添加調整,並獲得看起來不專業的抖動。

您會注意到 url 沒有改變。 要設置它,請使用return window.history.pushState(null, null, target); 相反,手動將 url 添加到歷史堆棧中。

完畢!

其他注意事項:

1) 使用.on方法是最新的(截至 2015 年 1 月)jquery 方法,它比.bind.live甚至.click更好,原因我會留給你找出來。

2) navOffset 值可以在函數內部或外部,但您可能希望它在外部,因為您很可能會引用其他函數/DOM 操作的垂直空間。 但我把它留在里面,使它整齊地成為一個功能。

$("#YOUR-BUTTON").on('click', function(e) {
   e.preventDefault();
   $('html, body').animate({
        scrollTop: $("#YOUR-TARGET").offset().top
     }, 300);
});
// styles.css
html {
    scroll-behavior: smooth
}

來源: https : //www.w3schools.com/howto/howto_css_smooth_scroll.asp#section2

如果您下載了 jquery 緩動插件(檢查出來) ,那么您只需要將其添加到您的 main.js 文件中:

$('a.smooth-scroll').on('click', function(event) {
    var $anchor = $(this);
    $('html, body').stop().animate({
        scrollTop: $($anchor.attr('href')).offset().top + 20
    }, 1500, 'easeInOutExpo');
    event.preventDefault();
});

並且不要忘記將平滑滾動類添加到您的 a 標簽中,如下所示:

 <li><a href="#about" class="smooth-scroll">About Us</a></li>

我把它結合起來,這就是結果——

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

我測試了它,它工作正常。 希望這會幫助某人:)

onetrickpony發布的內容是可以的,但是如果您想要更通用的解決方案,則可以使用下面的代碼。

除了選擇錨點的id ,您還可以讓它更標准一些,只需選擇<a> -Tag 的屬性name 這將使您免於編寫額外的id標簽。 只需將 smoothscroll 類添加到導航欄元素即可。

改變了什么

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

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

最終代碼

/* 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;

  });
});

使用此代碼,該 ID 將不會出現在鏈接上

    document.querySelectorAll('a[href^="#"]').forEach(anchor => {
        anchor.addEventListener('click', function (e) {
            e.preventDefault();

            document.querySelector(this.getAttribute('href')).scrollIntoView({
                behavior: 'smooth'
            });
        });
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM