2016-05-06 103 views
0

我有以下問題。我想添加一個類.orange到列表項,並在滾動到達特定元素時將其移除。jquery在滾動位置添加和刪除類

enter image description here

<style> 
    .orange { 
     background-color: orange; 
    } 
</style> 

<ul class="navbar-custom clearfix"> 
    <li> 
     <a href="#first-section"></a> 
    </li> 
    <li> 
     <a href="#second-section"></a> 
    </li> 
    <li> 
     <a href="#third-section"></a> 
    </li> 
    <li> 
     <a href="#fourth-section"></a> 
    </li> 
</ul> 

<section id="first-section"></section> 
<section id="second-section"></section> 
<section id="third-section"></section> 
<section id="fourth-section"></section> 

<script type="text/javascript"> 
    var $sec = $("section"), 
     handle = null; 
    var $w = $(window).scroll(function() { 
     clearTimeout(handle); 
     handle = setTimeout(function() { 
     var top = $w.scrollTop(); 
     // within the `setTimeout` context: 
     var $f = $sec.filter(function() { 
      return $(this).offset().top + $(this).height() >= top; 
     }).first(); 
     $items.removeClass('orange').eq($sec.index($f)).addClass('orange'); 
     }, 40); 
    }).scroll(); 
</script> 

回答

1

你需要找到元素,當滾動達到元素,在屏幕上顯示的元素,突出顯示圖標的位置。

$(window).scroll(function() { 
 
    var winHeight = $(this).height(); 
 
    var scrollTop = $(this).scrollTop(); 
 
    
 
    $("section").each(function(index){ 
 
     var elemHeight = $(this).height(); 
 
     var elementTop = $(this).position().top; 
 

 
     if (elementTop < scrollTop + winHeight && scrollTop < elementTop + elemHeight) 
 
      $(".navbar > li").eq(index).addClass("current"); 
 
     else 
 
      $(".navbar > li").eq(index).removeClass("current"); 
 
    }); 
 
});
.navbar { 
 
    position: fixed; 
 
    top: 30px; 
 
    right: 0px; 
 
    font-size: 20px; 
 
} 
 
    
 
.navbar > .current { 
 
    color: red; 
 
} 
 
    
 
section { 
 
    height: 500px; 
 
} 
 

 
section:nth-child(odd) { 
 
    background: #2196F3; 
 
} 
 

 
section:nth-child(even) { 
 
    background: #00BCD4; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<ul class="navbar"> 
 
    <li></li> 
 
    <li></li> 
 
    <li></li> 
 
    <li></li> 
 
</ul> 
 
<div class="container"> 
 
    <section></section> 
 
    <section></section> 
 
    <section></section> 
 
    <section></section> 
 
</div>