簡體   English   中英

Javascript getBoundingClientRect()-適用於類的多個實例

[英]Javascript getBoundingClientRect() - apply to multiple instances of class

我一直在嘗試使用一個函數來檢測元素是否在視口中:

function isElementInViewport (el) {
    var rect = el[0].getBoundingClientRect();
    return (rect.top>-1 && rect.bottom <= $(window).height());
}
var s= $('.special'),
    y = $('.status');

$(window).on('scroll resize', function(){
    if(isElementInViewport(s))
    {
        setTimeout(function(){
            if(isElementInViewport(s))
            {
            var offer_id = s.data("offer-id");
          alert(offer_id);
            y.text('Yes');
        }
      }, 3000);
    }
    else
    {
        y.text('No');
    }
});

不幸的是,這似乎只對“特殊”類的第一個實例起作用。 我如何將其應用於該類的所有實例?

請注意,我添加了3秒的延遲,以防止快速滾動觸發它。

這是我的進度的jsfiddle: http : //jsfiddle.net/azjbrork/6/

使用jquery each我們可以在.special類的每個實例上運行該函數,並相應地進行報告(以下代碼段):

 function isElementInViewport(el) { var rect = el[0].getBoundingClientRect(); return (rect.top > -1 && rect.bottom <= $(window).height()); } var s = $('.special'), y = $('.status'); $(window).on('scroll resize', function() { s.each(function() { var $this = $(this); if (isElementInViewport($this)) { setTimeout(function() { if (isElementInViewport($this)) { var offer_id = $this.data("offer_id"); // advise using an underscore instead of a hyphen in data attributes // alert(offer_id); // reported in text below y.text('Yes : ' + offer_id); } }, 200); } else { // y.text('No'); // omit this line otherwise it will always report no (subsequent out of screen divs will overwrite the response) } }); }); 
 .special { width: 80px; height: 20px; border: 1px solid #f90; margin-top: 200px; } .status { position: fixed; right: 2em; top: 1em; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class='special' data-offer_id='a'></div> <div class='special' data-offer_id='b'></div> <div class='special' data-offer_id='c'></div> <div class='special' data-offer_id='d'></div> <div class='special' data-offer_id='e'></div> <div class='special' data-offer_id='f'></div> <div class='status'></div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM