http://www.ruanyifeng.com/blog/2016/11/intersectionobserver_api.html
判斷元素是否在可視區(qū)域內(nèi):
方法一:
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')
)