http://www.ruanyifeng.com/blog/2016/11/intersectionobserver_api.html
判断元素是否在可视区域内:
方法一:
function isInSight(el) {
const bound = el.getBoundingClientRect();
const clientHeight = window.innerHeight;
//如果只考虑向下滚动加载
//const clientWidth = window.innerWeight;
if ( (bound.top + bound.height) < 0 ){
return true;
} else {
return false;
}
}
window.addEventListener('scroll', function(){
let obj = document.querySelector('.parent');
console.log(isInSight(obj))
})
方法二:
var intersectionObserver = new IntersectionObserver(
function (entries){
// 如果不可见,就返回
if ( entries[0].intersectionRatio <= 0 ){
console.log('不可见')
} else {
console.log('可见')
}
}
)
//开始观察
intersectionObserver.observe(
document.querySelector('.parent')
)