gpt4 book ai didi

javascript - 如何在滚动时通过类名检查 div 在屏幕上是否可见?

转载 作者:行者123 更新时间:2023-11-28 09:05:12 25 4
gpt4 key购买 nike

就像检查下面的“演示 div”

<div class="call" style="margin-top:100px;">
hi
</div>
<div class="call" style="margin-top:900px;">
hello
</div>

如果屏幕上的任何上面的 div 使用类名返回 true,而滚动时我使用下面的脚本,它总是返回 true,如何修复它?

<script>
jQuery.expr.filters.offscreen = function(el) {
return (
(el.offsetLeft + el.offsetWidth) < 0
|| (el.offsetTop + el.offsetHeight) < 0
|| (el.offsetLeft > window.innerWidth || el.offsetTop > window.innerHeight)
);
};

$(window).scroll(function () {
alert($('.call').is(':offscreen'))
});
</script>

最佳答案

试试这个

$(document).scroll(function () {
if (isOnScreen($('.call:eq(0)'))) {
// $('.call:eq(0)') is visible on screen
}

});

//this function return element is currently visible on screen or not in true / false
function isOnScreen(elem) {
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + $(window).height();

var elemTop = $(elem).offset().top;
var elemBottom = elemTop + $(elem).height();

return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}

用于演示

<div class="call" style="margin-top: 100px;">
hi
</div>
<label class="label1" style="margin-top: 500px;">
</label>
<label class="label2" style="margin-top: 20px;">
</label>
<div class="call" style="margin-top: 500px;">
hello
</div>
<script type="text/javascript">
$(document).scroll(function () {
if (isOnScreen($('.call:eq(0)'))) {
$('.label1').text('first div show') // if first call class div is visible msg display in lable
}
else {
$('.label1').text('first div hide')
}
if (isOnScreen($('.call:eq(1)'))) {
$('.label2').text('second div show')// if second call class div is visible msg display in lable
}
else {
$('.label2').text('second div hide')
}

});
function isOnScreen(elem) {
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + $(window).height();

var elemTop = $(elem).offset().top;
var elemBottom = elemTop + $(elem).height();

return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}
</script>

关于javascript - 如何在滚动时通过类名检查 div 在屏幕上是否可见?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17248207/

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