js IntersectionObserver api
API
const options = {
root: null,
threshold: [0, 0.5, 1],
rootMargin: '30px 100px 20px'
}
var io = new IntersectionObserver(callback, options)
io.observe(document.querySelector('img')) 开始观察,接受一个DOM节点对象
io.unobserve(element) 停止观察 接受一个element元素
io.disconnect() 关闭观察器
var io = new IntersectionObserver((entries)=>{
console.log(entries)
})
io.observe($0)
boundingClientRect 目标元素的矩形信息
intersectionRatio 相交区域和目标元素的比例值 intersectionRect/boundingClientRect 不可见时小于等于0
intersectionRect 目标元素和视窗(根)相交的矩形信息 可以称为相交区域
isIntersecting 目标元素当前是否可见 Boolean值 可见为true
rootBounds 根元素的矩形信息,没有指定根元素就是当前视窗的矩形信息
target 观察的目标元素
time 返回一个记录从IntersectionObserver的时间到交叉被触发的时间的时间戳
图片懒加载运用
const io = new IntersectionObserver(callback)
let imgs = document.querySelectorAll('[data-src]')
function callback(entries) {
entries.forEach(item => {
if (item.isIntersecting) {
item.target.src = item.target.dataset.src
io.unobserve(item.target)
}
})
}
imgs.forEach(item => {
io.observe(item)
})
实践
我想做一个类似滑动,然后fixed在旁边的一种布局,想了想可以用此API实现,话不多说直接上代码。
export default class Aside extends Vue {
@Ref('hotRef') readonly hotRef!: HTMLElement
categoryFixed: boolean = true
mounted() {
const options: IntersectionObserverInit = {
root: null,
rootMargin: '230px 0px 0px 0px',
}
let io = new IntersectionObserver(this.callback, options)
io.observe(this.hotRef)
}
callback(v: IntersectionObserverEntry[]) {
this.categoryFixed = v[0].isIntersecting
}
}
通过categoryFixed
动态添加fixed定位即可~