简体   繁体   中英

on scroll set background-color on element box which is on top

I think the code shows what I am trying to do.

html:

<div id="one" class="box"></div>
<div id="two" class="box"></div>
<div id="thr" class="box"></div>
<div id="fou" class="box"></div>
<div id="fiv" class="box"></div>
<div id="six" class="box"></div>

script:

$(document).ready(function(){
    $(window).scroll(function(){
        $('.box').each(functions(e){
            if($(this).offset().top <= 0) {
                $(this).css('background-color','green');
            }
        });
    });
});

css:

div {
    position:relative;
    width:100%;
    height:300px;
    background-color:orange;
    margin:10px;
}

fiddle: http://jsfiddle.net/VR4ca/

So while scrolling the box on top should become the background-color green until the next box reaches the top of the window

Please help

it is not even working just with the first box http://jsfiddle.net/VR4ca/2/

If you want to always have the upper green so something like this:

$(document).ready(function(){
    $(window).scroll(function(){
        num=Math.ceil($(window).scrollTop()/$('.box').height());
        $('.box').css('background-color','orange');
        $('.box:nth-child('+num+')').css('background-color','green');      
    });
});

demo

cleaner solution:

$(document).ready(function(){
    $(window).scroll(function(){
        num=Math.trunc($(window).scrollTop()/$('.box').height());
        $('.box').css('background-color','').eq(num).css('background-color','green');      
    });
});

demo

$(window).scroll(function(){
    var pixelScrolled = $(window).scrollTop();
    $( ".box" ).each(function( index ) {
    var currentHeight = $(this).height();
        if (pixelScrolled >= index * currentHeight)
            $(this).addClass('active');
        else
            $(this).removeClass('active');
    });
});

Instead of .height() you can use .outerHeight() or .outerHeight(true) to include the size of border, padding and margin.

See demo :

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM