Jquery在滚动位置添加和删除类

时间:2016-05-06 11:50:46

标签: jquery scroll

我有以下问题。我想在list-item中添加一个类.orange,如果滚动到达特定元素,则在滚动时将其删除。

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 个答案:

答案 0 :(得分:1)

您需要找到元素的位置,当滚动到达屏幕中显示的元素和元素时,突出显示图标。

&#13;
&#13;
$(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");
    });
});
&#13;
.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;
}
&#13;
<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>
&#13;
&#13;
&#13;