简体   繁体   English

Javascript getBoundingClientRect()-适用于类的多个实例

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

I've been trying to use a function to detect if an element is in the viewport: 我一直在尝试使用一个函数来检测元素是否在视口中:

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');
    }
});

Unfortunately this only seems to work for the first instance of the class 'special'. 不幸的是,这似乎只对“特殊”类的第一个实例起作用。 How do I get it to apply to all instances of that class? 我如何将其应用于该类的所有实例?

Note that I've added a 3 second delay, to prevent fast scrolling from triggering it. 请注意,我添加了3秒的延迟,以防止快速滚动触发它。

Here's the jsfiddle of my progress: http://jsfiddle.net/azjbrork/6/ 这是我的进度的jsfiddle: http : //jsfiddle.net/azjbrork/6/

using jquery each we can run the function on each instance of the .special class and report back accordingly (snippet below) : 使用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