gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:31:38 30 4
gpt4 key购买 nike

我一直在尝试使用一个函数来检测元素是否在视口(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');
}
});

不幸的是,这似乎只适用于“特殊”类的第一个实例。我如何让它应用于该类的所有实例?

请注意,我添加了 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>

关于Javascript getBoundingClientRect() - 适用于类的多个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42175505/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com