zoukankan      html  css  js  c++  java
  • 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定位即可~

  • 相关阅读:
    在C#中,不安装Oracle客户端如何连接Oracle数据库
    敏捷宣言(四) 猪和鸡的故事
    敏捷宣言(六) 单单有敏捷就够了吗?
    敏捷宣言(五) 看板是另外一种敏捷实践
    敏捷宣言(七) 软件系统
    小白知识摘录__进程和线程
    Linux系统修改/etc/sysconfig/i18n文件,桌面无法正常显示
    小白知识摘录__环境变量
    hive表查询中文显示乱码
    3月10日晚
  • 原文地址:https://www.cnblogs.com/smzd/p/11911434.html
Copyright © 2011-2022 走看看