我有一个侧边栏,可以让我捕捉到页面主要部分的内容。当用户向下滚动时,侧边栏会粘在页面上
<div class="sidebar" style="width: 16%;float: left;position: absolute;margin-top:15px;">
<div class="jump_stage" onclick="window.location.href='#div1'">div1</div>
<div class="jump_stage" onclick="window.location.href='#div2'">div2</div>
<div class="jump_stage" onclick="window.location.href='#div3'">div3</div>
<div class="jump_stage" onclick="window.location.href='#div4'">div4</div>
<div class="jump_stage" onclick="window.location.href='#div5'">div5</div>
</div>
<div class="main_body">
<div id="div1" class="content">Div 1 content</div>
<div id="div2" class="content">Div 2 content</div>
<div id="div3" class="content">Div 3 content</div>
<div id="div4" class="content">Div 4 content</div>
<div id="div5" class="content">Div 5 content</div>
</div>
我想在页面到达 div 时向侧边栏添加一个事件类(或类似的东西)。我不知道从哪里开始,到目前为止,搜索并没有给我带来好运。
我是否必须计算出页面和每个元素的高度,并在滚动达到特定数字时添加类?任何帮助将不胜感激!
最佳答案
我修改了this jsfiddle 来完成您想要实现的目标,您可以 view here.
我所做的只是修改滚动时要执行的操作。
$( window ).scroll(function(){
$('.box').each(function(){
if ($(this).isOnScreen()){
$(this).addClass('orange');
}
});
});
这将文本,当窗口滚动时,屏幕上的每个单独的框是否实际上在视口(viewport)中,由我从原始 jsfiddle 中使用的函数确定,如下所示。
$.fn.isOnScreen = function(){
var win = $(window);
var viewport = {
top : win.scrollTop(),
left : win.scrollLeft()
};
viewport.right = viewport.left + win.width();
viewport.bottom = viewport.top + win.height();
var bounds = this.offset();
bounds.right = bounds.left + this.outerWidth();
bounds.bottom = bounds.top + this.outerHeight();
return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));
};
如果此代码返回 true,则该元素在视口(viewport)中,并且它将添加类“orange”。
很难看出这真的有效,所以如果你愿意,你可以尝试将第 3 行修改为 if ($(this).isOnScreen() === false){
然后你可以看到,当您向下滚动时,只有屏幕外的元素才会显示为橙色。
关于jquery - 滚动经过 DIV 时将类添加到侧边栏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21938429/