2016-11-04 50 views
0

我正在創建我的第一個單頁項目,所以我希望能夠輕鬆滾動。如何在滾動到定位點之前關閉導航?

HTML:

<nav> 
    <ul> 
    <li><a href="#top">Top</a></li> 
    <li><a href="#middle">Middle</a></li> 
    <li><a href="#bottom">Bottom</a></li> 
    </ul> 
    <span id="hamburger">Hamburger Icon</span> 
</nav> 

JQuery的:

$("#hamburger").on("click", function() { 
    $("nav ul li").toggleSlide("normal"); 
}); 

//Snipet code from CSS-Tricks 

$(function() {   
     $('a[href*="#"]:not([href="#"])').click(function() { 
      //Added code 
      if($('nav ul').is(':visible')) { 
       $('nav').slideToggle("fast"); 
      } 
      //End added code 
      if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) { 
       var target = $(this.hash); 
       target = target.length ? target : $('[name=' + this.hash.slice(1) +']'); 
       if (target.length) { 
        $('html, body').animate({ 
         scrollTop: target.offset().top 
        }, 700); 
        return false; 
       } 
      } 
     }); 
    }); 

我被堵在移動第一個模板。基本上,當我點擊漢堡圖標時,菜單顯示爲「塊」。當我選擇一個錨點時,它應該關閉菜單並滾動到錨點。事情似乎很簡單,但它並不像我想的那樣運作良好。當我點擊定位點時,菜單消失並很好地滾動到我的預定點。但是,無論我如何點擊「漢堡圖標」,現在菜單都無法再次打開。

順便說一句,我剛開始使用JQuery,所以我希望看到一個明確的指示。謝謝。

回答

1

將slideToggle用於您的兩個動畫。我也會動畫nav ul而不是nav ul li那樣,你只是動畫一個項目而不是多個項目,沒有理由。所以在你的css中將nav ul更改爲display:none而不是nav ul li。此外,可能沒有理由檢查nav ul是否可見,因爲無論如何點擊菜單中的鏈接,您將滾動到某個部分。這樣說來,你可以只使用下面的代碼:

這裏是工作提琴Fiddle Demo

$("#hamburger").on("click", function() { 
    $("nav ul").slideToggle("normal"); 
}); 

//Snipet code from CSS-Tricks 

$(function() {   
     $('a[href*="#"]:not([href="#"])').click(function() { 

      //Added code 
      $('nav ul').slideToggle("fast"); 

      //End added code 
      if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) { 
       var target = $(this.hash); 
       target = target.length ? target : $('[name=' + this.hash.slice(1) +']'); 
       if (target.length) { 
        $('html, body').animate({ 
         scrollTop: target.offset().top 
        }, 700); 
        return false; 
       } 
      } 
     }); 
    }); 
+0

哇,謝謝。你喝得太多了嗎? :) –