简体   繁体   English

使用jquery从窗口顶部到达200px时如何更改div的类?

[英]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:我在一个网页上有 5 个框,你可以在这里看到:

http://demo.axistheme.com/methodology/Wakeup-Method.html . 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.第一个框的文本 01 为黄色背景,第二个框的文本为 02、03 等,背景为灰色。

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?滚动窗口时,如何在其他每个框(一个一个)到达窗口顶部下方 200 像素处更改它们的背景颜色?

You need to check - whenever the window is scrolled - if any of the elements are less than 200px from the top of the viewport.您需要检查 - 无论何时滚动窗口 - 是否有任何元素距视口顶部小于200px

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 ).要确定每个元素相对于视口的垂直偏移位置,您可以从每个元素相对于文档的垂直偏移位置 ( .offset().top ) 中减去窗口垂直滚动位置 ( $(window).scrollTop )。

ie. 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.您可以将 offset() 与 $(window).scrollTop() 结合使用来确定元素的位置。

    $('.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/在此处查看一个工作示例: https : //jsfiddle.net/jkrielaars/yt584kLz/2/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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