检查元素是否位于当前视窗(可用于lazyload, infinite scroll等常见功能)

原文来自:snippets.barretlee.com,只是为了自己学习收集特意fork了一遍。如有侵权,联系删除:i@webcliwn.net

1
2
3
4
5
6
7
8
function isInViewport(el) {
var rect = el.getBoundingClientRect();

return rect.bottom > 0 &&
rect.right > 0 &&
rect.left < (window.innerWidth || document. documentElement.clientWidth) &&
rect.top < (window.innerHeight || document. documentElement.clientHeight);
}

Example Usage:

1
2
3
window.addEventListener('scroll', function() {
isInViewport(el);
})