IntersectionObserver 可以用于检测元素是否进入视口,用于实现无限滚动、懒加载等。
一 基本使用 var observer = new IntersectionObserver((entries, observe) => {
entries.forEach((i) => {
// 通过滚动判断是否是当前的监听对象
if (i.isIntersecting) {
//已经在视图窗口显示要进行的操作
console.log("已在视图窗口显示")
//移除对元素的监听
observer.unobserve(i.target)
}
})
})
document.querySelectorAll('div').forEach((i) => {
//要监听的元素
observer.observe(i)
})
二 图片懒加载
const root = document.getElementsByTagName('ul')[0]
const options = {
root: root,
// 这里是一个数组可以指定多个比例类似[0.25, 0.5, 0.75, 1]
// 当目标元素 0%、25%、50%、75%、100% 可见时,会触发回调函数
threshold: [0],
rootMargin:"0px"
}
const lazyIntersection = new IntersectionObserver(entires => {
entires.forEach((item,index) => {
if(item.isIntersecting) {
console.log("已在视图窗口显示")
item.target.src = item.target.getAttribute('data-src')
// 移除 lazyIntersection.unobserve(item.target) }
})
}, options)
// doucument.getElementsByTagName()获取的是一个元素DOM节点的伪数组,无法进行数组的遍历
// 我们可以使用Array.from()将伪数组转化为真数组进行数组操作
let data = Array.from(document.getElementsByTagName('img'))
data.forEach(item => {
lazyIntersection.observe(item)
})
对了 getBoundingClientRect() 方法返回元素的大小及其相对于视口的位置。
getBoundingClientRect() 方法也可以判断元素是否在可视区
function isElView(el) {
var top = el.getBoundingClientRect().top // 元素顶端到可见区域顶端的距离
var bottom = el.getBoundingClientRect().bottom // 元素底部端到可见区域顶端的距离
var se = document.documentElement.clientHeight // 浏览器可见区域高度。
if (top < se && bottom > 0) {
return true
} else if (top >= se || bottom <= 0) {
// 不可见
} return false
}