2012-02-28 77 views
1

我已將會話設置爲行。滾動高亮標題

<div class="container" id="session1"> 
    <div class="row session"> 
    <div class="fourcol"> 
     <h2>Session 3:</h2> 
    </div> 

    <div class="fourcol last"> 
     <p> Information about session </p> 
    </div> 

    </div> 
</div> 

我有很多這些會議的,需要一種方式來突出顯示你正在閱讀會議1.我想你滾過到一個.selected類添加到<h2 class="selected">Session 3:</h2>

我希望這也將添加.selected類,如果有任何傳入的錨鏈接。 to/sessions#session1因爲它必須'滾動'到那個位置

任何幫助都會很棒。謝謝。

回答

6

我會推薦看一下jQuery Waypoints,它正是你想要的,它很容易使用。

Here's an example我做了,當我使用jQuery Waypoint將元素滾動到視口中時,我添加了.selected類。


你當然也可以自己做,但你會做同樣的事情Waypoint已經在做。
首先在文檔或所需元素上使用.scroll event來捕獲所需的特定事件。

$(document).scroll(function(e){ 
}); 

然後使用.scrollTop來檢查你在哪裏,並添加「邊界」的元素必須是內,根據視口,即窗口。

$(document).scroll(function(e){ 
    var bound_top = $(this).scrollTop(), 
     bound_bottom = bound_top + $(window).height(); 
}); 

然後檢查每個標題/部分元素,看看他們是那些邊界

$(document).scroll(function(e){ 
    var bound_top = $(this).scrollTop(), 
     bound_bottom = bound_top + $(window).height(); 

    $("h2").each(function(){ 
     if( 
      $(this).position().top >= bound_top && 
      $(this).position().top + $(this).outerHeight() <= bound_bottom 
     ){ 
      $(this).addClass("selected"); 
     }else{ 
      $(this).removeClass("selected"); 
     } 
    } 
}); 

內它看起來有點像in this example我做了。

這種方法可以讓你按照你想要的方式完成任務。
jQuery Waypoint是一個不錯的選擇。

+0

非常感謝ShadowScripter。我不知道航點,我不知道如何實施,所以謝謝你給我看。再次感謝! – uriah 2012-02-29 07:10:44