2015-12-15 85 views
6

我有一个ID添加类在一个div <div id="Section1"> abc </div>和纽带<a id="link" href="#Section1">Section1</a>当页面滚动达到特定ID

问:当我滚动页面和页面范围的ID #Section1类应在链接添加,链接想<a id="link" href="#Section1" class="ok">Section1</a>

+0

为了更好的理解,请提供一个**工作演示* *(*代码片段,jsfiddle ... *) –

+0

你尝试过使用jquery ScrollTo()吗? –

+0

这可能会给你一个想法.. http://lions-mark.com/jquery/scrollTo/ –

回答

4

你可以使用这样的:

$(window).scroll(function (event) { 
    var scroll = $(window).scrollTop(); 
    $('#link').toggleClass('ok', 
    //add 'ok' class when div position match or exceeds else remove the 'ok' class. 
     scroll >= $('#Section1').offset().top 
    ); 
}); 
//trigger the scroll 
$(window).scroll();//ensure if you're in current position when page is refreshed 

请参阅该文档为toggleClass

+0

#Bhojendra好的类应该加入链接,即有id =“link”Section1

+0

哦!忽视。更新。 –

+0

是的,我更新的问题,以更好地了解 –

0

如果有人正在寻找一个不错的库,我通常使用waypoints.js + inview这种类型的滚动事件。它提供了一个很好的API,知道什么时候元素进入和离开,等

示例代码:

var inview = new Waypoint.Inview({ 
    element: $('#inview-example')[0], 
    enter: function(direction) { 
     notify('Enter triggered with direction ' + direction) 
    }, 
    entered: function(direction) { 
     notify('Entered triggered with direction ' + direction) 
    }, 
    exit: function(direction) { 
     notify('Exit triggered with direction ' + direction) 
    }, 
    exited: function(direction) { 
     notify('Exited triggered with direction ' + direction) 
    } 
}); 

它要求:

<script src="/path/to/lib/jquery.waypoints.min.js"></script> 
<script src="/path/to/shortcuts/inview.min.js"></script>