2017-08-02 86 views
0

我有我的導航欄這個代碼的網站,我做的:jQuery的平滑滾動不與引導4導航欄的工作

<body data-spy="scroll" data-target="#navbar" data-offset="20"> 
    <!-- navbar --> 
    <div id="home"> 
    <div id="navbar"> 
     <nav class="navbar navbar-toggleable-md navbar-light bg-faded hidden-sm-down fixed-top mb-0"> 
     <div class="container"> 
      <a class="navbar-brand" href="#">honesty</a> 
      <div class="navbar-collapse justify-content-end" id="navCollapse"> 
      <ul class="navbar-nav smooth-scroll"> 
       <li class="nav-item"> 
       <a class="nav-link smooth-scroll" href="#home">Home</a> 
       </li> 


       <li class="nav-item"> 
       <a class="nav-link smooth-scroll" href="#about">About</a> 
       </li> 


       <li class="nav-item"> 
       <a class="nav-link smooth-scroll" href="#portfolio">Portfolio</a> 
       </li> 


       <li class="nav-item"> 
       <a class="nav-link smooth-scroll" href="#contact">Contact</a> 
       </li> 
      </ul> 
      </div> 
     </div> 
     </nav> 
    </div> 
    </div> 

的scrollspy代碼does not工作

<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script> 
    <script> 
    $(document).ready(function() { 
     // Add smooth scrolling to all links 
     $("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 
     }); 
    }); 
    </script> 
(從W3Schools的網站得到的)

我真的不確定它是Bootstrap的導航欄導致問題還是我的jQuery或兩者的組合。我將不勝感激任何幫助。我也聽說scrollspy可能會混淆涉及導航欄和/或父元素的jQuery腳本。

請注意我用的引導4不3.

回答

0

的scrollspy的作品,你只需要分配ID要滾動的區域(每個導航欄項目對應一個id

例如,當您單擊About時,JQuery將在頁面上某處尋找id='about'

  • hash從在導航欄的About鏈路,這是'#about'
  • $(hash).offset().top找到頁面上的元素與id='about'並返回它的頂部座標來設定等於href。 JQuery動畫函數用於滾動到這些座標。

問題:

  • 目前你沒有,可以有針對性的任何標識,所以$(hash)不返回元素。

  • offset()然後在未定義的$(hash)上調用,這會產生錯誤。

  • 您不能在undefined上致電offset()


這裏是你的scrollspy代碼引導4工作演示:CodePen Demo


我也減去60個像素的動畫功能,像這樣:

$(hash).offset().top - 60 

這會讓您的滾動目標60px更高,這在這種情況下很有幫助,因此您的導航欄不會隱藏您要滾動的元素。

+0

這打破了我的Scrollspy,它沒有工作。這裏是一個小提琴: –

+0

你檢查了codepen嗎?它在那裏滾動。所有你需要的是滾動到的ID。你有一個導航欄滾動到當前不存在的頁面部分。您可以使用滾動所需的ID標記部分。另外,我沒有看到你的小提琴鏈接。 –