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

时间:2017-02-11 11:48:54

标签: javascript jquery getboundingclientrect

我一直在尝试使用函数来检测元素是否在视口中:

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秒延迟,以防止快速滚动触发它。

以下是我进步的问题:http://jsfiddle.net/azjbrork/6/

1 个答案:

答案 0 :(得分:2)

使用jquery each我们可以在.special类的每个实例上运行该函数并相应地向后报告(下面的代码段):

&#13;
&#13;
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)
    }
  });

});
&#13;
.special {
  width: 80px;
  height: 20px;
  border: 1px solid #f90;
  margin-top: 200px;
}
.status {
  position: fixed;
  right: 2em;
  top: 1em;
}
&#13;
<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>
&#13;
&#13;
&#13;