我通过AJAX加载元素。其中一些只有当你向下滚动页面时才能看到。有什么方法可以知道元素现在是否在页面的可见部分?
当前回答
在毫无成效地跑来跑去并使用了几个不工作的代码之后。这就是我使用Jquery实现垂直滚动可视性的方法。 将'#footerplace'替换为您想垂直跟踪的元素。
jQuery.expr.filters.offscreen = function(el) {
var rect = el.getBoundingClientRect();
console.log(rect)
console.log('window height', $(window).height());
return (
(rect.top <= $(window).height()) && (rect.bottom <= $(window).height())
);
};
$(document).scroll(function(){
if ($('#footerplace').is(':offscreen')){
console.log('this is true');
$('#footerplace').is(':offscreen');
} else {
console.log('this is false');
$('#footerplace').is(':offscreen');
}
其他回答
用香草语回答:
function isScrolledIntoView(el) {
var rect = el.getBoundingClientRect();
var elemTop = rect.top;
var elemBottom = rect.bottom;
// Only completely visible elements return true:
var isVisible = (elemTop >= 0) && (elemBottom <= window.innerHeight);
// Partially visible elements return true:
//isVisible = elemTop < window.innerHeight && elemBottom >= 0;
return isVisible;
}
jQuery Waypoints插件在这里做得非常好。
$('.entry').waypoint(function() {
alert('You have scrolled to an entry.');
});
在插件的站点上有一些例子。
我需要检查可滚动DIV容器内元素的可见性
//p = DIV container scrollable
//e = element
function visible_in_container(p, e) {
var z = p.getBoundingClientRect();
var r = e.getBoundingClientRect();
// Check style visiblilty and off-limits
return e.style.opacity > 0 && e.style.display !== 'none' &&
e.style.visibility !== 'hidden' &&
!(r.top > z.bottom || r.bottom < z.top ||
r.left > z.right || r.right < z.left);
}
我改编了这个简短的jQuery函数扩展,你可以自由使用(MIT许可)。
/**
* returns true if an element is visible, with decent performance
* @param [scope] scope of the render-window instance; default: window
* @returns {boolean}
*/
jQuery.fn.isOnScreen = function(scope){
var element = this;
if(!element){
return;
}
var target = $(element);
if(target.is(':visible') == false){
return false;
}
scope = $(scope || window);
var top = scope.scrollTop();
var bot = top + scope.height();
var elTop = target.offset().top;
var elBot = elTop + target.height();
return ((elBot <= bot) && (elTop >= top));
};
isScrolledIntoView是一个非常必要的函数,所以我尝试了它,它适用于不高于视口的元素,但如果元素比视口大,它就不起作用了。要解决这个问题,只需改变条件
return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
:
return (docViewBottom >= elemTop && docViewTop <= elemBottom);
请看这里的演示:http://jsfiddle.net/RRSmQ/