简体   繁体   中英

How to change class of a div when reach at 200px from top of the window using jquery?

I have 5 boxes on a webpage that you can see here:

http://demo.axistheme.com/methodology/Wakeup-Method.html .

The 1st box has the text 01 with a yellow background color and 2nd and the others have the text 02, 03 etc. with a gray background color.

When scrolling the window, how can I change the background color of each of the other boxes (one by one) at the point where they reach 200px beneath the top of the window?

You need to check - whenever the window is scrolled - if any of the elements are less than 200px from the top of the viewport.

To determine each element's vertical offset position relative to the viewport, you can subtract the window vertical scroll position ( $(window).scrollTop ) from each element's vertical offset position relative to the document ( .offset().top ).

ie. var offsetTopPosition = $(ELEMENT).offset().top - $(window).scrollTop();

Working Example:

 $(document).ready(function(){ $(window).scroll(function(){ $('div').each(function(){ var offsetTopPosition = $(this).offset().top - $(window).scrollTop(); if (offsetTopPosition < 100) { $(this).addClass('active'); } if (offsetTopPosition > 100) { $(this).removeClass('active'); } }); }); });
 div { width: 36px; height: 36px; line-height: 36px; margin-bottom: 200px; color: rgb(0,0,0); background-color: rgb(191,191,191); font-size: 24px; font-weight: bold; text-align: center; } .active { background-color: yellow; }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="active">1</div> <div>2</div> <div>3</div> <div>4</div> <div>5</div>

You can use offset() in combination with $(window).scrollTop() to determine the position of your elements.

    $('.box').each(function( index ) {
        var threshold = 200;
        var topOffset = $( this ).offset().top;
        if( topOffset - $(window).scrollTop() < threshold){
            $( this ).addClass('active');
       }else{
           $( this ).removeClass('active');
        }
    });

See a working example here: https://jsfiddle.net/jkrielaars/yt584kLz/2/

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