2015-12-15 157 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> 
相關問題