我已将会话设置为行。
<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
类。到/ sessions#session1因为它必须“滚动”到那个位置
任何帮助都会很棒。感谢。
答案 0 :(得分:6)
我建议您查看jQuery Waypoints,它正是您正在寻找的,而且它很容易使用。
Here's an example我做了,在使用jQuery Waypoints将元素滚动到视口中时添加.selected
类。
你当然可以自己做,但是你会做同样的事情.Wavepoint已经做了
首先在文档或所需元素上使用.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 Waypoints是一个很好的快速替代方案。