最近在做公司官网 web&H5 页面滚动显示出来给个小动画
之前了解的浏览器标准解决方案(不向下兼容)是 IntersectionObserver,是一个全局的侦听器,
但是每个页面去做一个实例去侦听当前对象也觉得太冗余了吧,并且在vue里面自己去操作dom对象也不是一个很优的选择,于是我们想到了vue自定义指令
我使用的动画是npm上下了个 animate.css, 当然你也可以自己写动画
思路:
1.创建一个观察者
2.制作vue指令,将vue返回的dom进行监听,并且写入暂存的属性值
3.well 为 IntersectionObserver 的回调参数,格式为数组,循环well
4.res 为每个 dom返回的封装对象
5.res.target 为 dom 实例 res.isIntersecting 判断是否相交
6. 添加动画 并且settimeout 延时一秒移除动画为了不重复动画,res.target.className.indexOf('animate__animated') < 0 也是为了不重复动画
let observer = new IntersectionObserver(well => {
well.forEach(res => {
const className = ` animate__animated ${res.target.attributes.animatename.value}`
if(res.isIntersecting && res.target.className.indexOf('animate__animated') < 0){
res.target.clas