像下面的“demo 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>
答案 0 :(得分:0)
试试这个
$(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));
}
for demo
<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>