我正在试图弄清楚在滚动期间如何检查DOM元素在Windows视口中是否可见,我一直在使用许多方法和许多插件而我无处可去。看起来当我将视口检查附加到window.scroll它只是不起作用:
$(window).scroll(function() {
if(checkIfXInViewport) {
// this is getting executed ALL THE TIME
} else {
// this never happens even if X is NOT in viewport }
}
});
以下是使用http://jsfiddle.net/tuT7U/(使用https://github.com/zeusdeux/isInViewport/)的示例。运行控制台,即使标题超出视口,它也始终返回“可见”....为什么?
我做错了什么?
答案 0 :(得分:0)
这是我用来检测何时至少50%的元素在视口中然后做某事。您可以进行调整以检测它变为可见的瞬间。
// Create jQuery Method
jQuery.fn.isOnScreen = function(){
var win = $(window);
var viewport = {
top : win.scrollTop(),
left : win.scrollLeft()
};
viewport.right = viewport.left + win.width();
viewport.bottom = viewport.top + win.height();
var elemtHeight = this.height()/2;
elemtHeight = Math.round(elemtHeight);r
var bounds = this.offset();
bounds.top = bounds.top + elemtHeight;
bounds.right = bounds.left + this.outerWidth();
bounds.bottom = bounds.top + this.outerHeight();
return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));
}
//Usage:
$(window).scroll(function(){
if( $('#your-element').isOnScreen() ){
// do something
}
else {
// element not in viewport
}
});