发现这个非常好的问题/答案重新扩展jQuery以确定元素是否在屏幕外:
如何检查元素是否在屏幕外
还发现了这篇文章,但无法使用来解决问题:
http://code.tutsplus.com/tutorials/dissecting-jquery-filters--net-13954
使用scuker的(接受答案)代码,当黄色DIV从屏幕上滚动时,这应该会发出警报(并隐藏元素)。事实并非如此。找不到问题。
jsFiddle(对于喜欢的人)
Raw jQuery / CSS / HTML Code (S.O. Embedded):
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)
);
};
var d1=0,d2=0,d3=0,dir='dn',cpos=0,lpos=0;
var div1=$('#d1'),div4=$('#d4'),div5=$('#d5');
$(window).scroll(function() {
cpos = $(window).scrollTop(); //get current scroll position
div4.html(cpos);
dir = (cpos>lpos) ? 'dn': 'up'; //get scroll direction
//div5.html(dir);
if (dir=='dn'){
d1 = cpos + (cpos*1.25);
}else{
d1 = cpos - (cpos*1.25);
}
div1.html(d1); //update pos numbers
div1.dequeue().stop().animate({'top':d1+'px'});
lpos = cpos; //store for line 6
div1.is(':offscreen').hide();
div5.html( (div1.is(':offscreen')) ? 'yup':'no' );
});
html{height:1800px;}
body{background: url('http://placekitten.com/g/500/500') no-repeat center center fixed;background-size:cover;}
.divs{position:fixed;top:0;height:120px;width:60px;}
#d1{background:yellow;}
#d4{background:wheat;left:380px;}
#d5{background:white;left:440px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div id="d1" class="divs"></div>
<div id="d4" class="divs"></div><!-- curr window scrollTop -->
<div id="d5" class="divs"></div><!-- curr scroll direction -->
编辑、更新
不确定是否使用:offscreen
来测试元素是否"屏幕外"——如原始答案中所述
这取决于你对"屏幕外"的定义视口中,还是在页面的定义边界内?
写一张支票看看它是否在屏幕外(不是考虑视口…)-标志物
在jsfiddle中,:offscreen
元素被隐藏后,div1.is(':offscreen')
似乎返回false
,导致div5
html
为"no"。相反,可以使用jQuery:隐藏选择器来检查div1
是否为:hidden
jQuery.is()返回Boolean
。
在
div1.is(':offscreen').hide();
.hide()
不与this
元素连锁;而是链接到is()
的Boolean
返回值?
尝试,更新
div1.filter(function() {
return $(this).is(":offscreen")
}).hide();
// added
// modify `div5` `html` by checking if `div1` is `:hidden`
div5.html( div1.is(':hidden') ? 'yup':'no' );
jsfiddlehttp://jsfiddle.net/guest271314/Lzq85592/5/