簡體   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