繁体   English   中英

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

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

我在一个网页上有 5 个框,你可以在这里看到:

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

第一个框的文本 01 为黄色背景,第二个框的文本为 02、03 等,背景为灰色。

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

您需要检查 - 无论何时滚动窗口 - 是否有任何元素距视口顶部小于200px

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

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

工作示例:

 $(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>

您可以将 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');
        }
    });

在此处查看一个工作示例: https : //jsfiddle.net/jkrielaars/yt584kLz/2/

暂无
暂无

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

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