js IntersectionObserver api
2024-09-05 23:03:59
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定位即可~
最新文章
- Oracle中DBLink的使用
- Vim命令合集
- 【python游戏编程之旅】第九篇---嗷大喵快跑小游戏开发实例
- [U3D 添加大地、天空,用第一视角看看自己做的世界]
- 基础02 Java 跨平台原理
- Codeforces Round #313 (Div. 1) C. Gerald and Giant Chess
- BZOJ 2668 交换棋子(费用流)
- java 的文件读取操作
- lintcode : 空格替换
- 使用RecyclerView实现瀑布流的效果
- (Problem 22)Names scores
- VUE项目 npm run build卡住不动,也不报错
- Linux 文件系统管理
- cakePHP 分页栏
- C、C ++的内存模型
- RabbitMq Queue一些方法及参数
- zabbix3.0.4安装趋势图集中显示插件graphtrees
- java编译 Error: Could not find or load main class java执行包main方法
- c++的class声明及相比java的更合理之处
- 关于bfs与dfs的标记区别