2017-03-04 67 views
0

我剛開始學習jQuery和JS特定區間的底部,現在我在做一些基本的東西困難。如何改變靜態到固定的位置,當達到

我想使靜態導航欄成爲固定的,當窗口到達.hero-fullscreen節結束並返回到靜若沒有。

$(window).on("scroll", function() { 
 

 
    var navbar = $(".navbar"); 
 
    if (navbar.offset().top > 150) { 
 
    navbar.addClass(".navbar-fixed"); 
 
    } else { 
 
    navbar.removeClass(".navbar-fixed"); 
 
    } 
 

 
});
.navbar { 
 
    display: block; 
 
    height: 50px; 
 
    width: 100%; 
 
    background-color: #000; 
 
} 
 

 
.navbar-static { 
 
    position: static; 
 
} 
 

 
.navbar-fixed { 
 
    position: fixed; 
 
} 
 

 
.hero-fullscreen { 
 
    height: 100vh; 
 
    width: 100%; 
 
    background-color: red; 
 
} 
 

 
.random-section { 
 
    height: 100vh; 
 
    width: 100%; 
 
    background-color: blue; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<nav class="navbar navbar-static"></nav> 
 
<section class="hero-fullscreen bg-image"></section> 
 
<section class="random-section"></section>

現在,我的問題是,不是.top > 150,應該是什麼有如此的navbar當到達.hero-fullscreen(紅色的)部分的底部就固定了?

謝謝!

+0

僅供參考您的HTML缺少'class'屬性的一些結束引語 –

+0

如果您包含codepen或jsfiddle,我將能夠更快地回答這個問題。另外,我很確定你的代碼片斷已被破壞 – Anthony

+0

謝謝大家指出我這一點,我修復了代碼,現在片段顯示很好。 –

回答

1

基本上你需要做兩件事情:

  1. 找出視口的高度
  2. 始終保持跟蹤,其中 滾動條是

像這樣

window.addEventListener('load', getWindowHeight); 
    window.addEventListener('resize', getWindowHeight); 

    var endPos; 

    function getWindowHeight(){ 
     var hei = window.innerHeight; 
     endPos = hei + 50; 
    } 

    document.addEventListener('scroll', trackScroll); 

    var navBar = document.getElementById('navbar'); 

    function trackScroll() { 
     var scrollPos = document.body.scrollTop(); 
     if (scrollPos > endPos) { 
     navBar.style.position = 'fixed'; 
     } else { 
     navBar.style.position = 'static'; 
     } 
    } 

但是,我已經做到這一點,你必須給你的導航離子元素的navbar一個id,而不是一個class

  1. getWindowHeight滿足第一個要求。
  2. trackScroll滿足第二要求,並進行必要的更改。
相關問題