滚动浏览DIV时,将类添加到侧边栏

时间:2014-02-21 15:28:29

标签: jquery html css

我有一个侧边栏,允许我捕捉到页面主要部分的内容。当用户向下滚动时,侧边栏会粘到页面上

<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时,我想在侧边栏中添加一个活动类(或类似的东西)。我不知道从哪里开始,到目前为止,寻找它并没有给我带来任何好运。

当滚动到达特定数字时,我是否必须计算页面和每个元素的高度并添加类?任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

我修改了this jsfiddle来完成你想要实现的目标,你可以view here.

我所做的就是修改滚动时的操作。

$( window ).scroll(function(){
    $('.box').each(function(){
        if ($(this).isOnScreen()){
            $(this).addClass('orange');
        }
    });
});

当滚动窗口时,这将显示屏幕上的每个单独的框是否实际上在视口中,由我在原始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){然后你可以看到当你向下滚动时只有屏幕上的项目是橙色的。< / p>