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定位即可~

  • 相关阅读:
    python2.7升python3.2
    SQL-基础学习使用的数据库资料
    SQL-基础学习2--ORDER BY ,DESC,WHERE, BETWEEN,AND ,OR ,IN ,NOT
    SQL-基础学习1--SELECT,LIMIT,DISTINCT,注释
    Python之Django-part 1
    python--文本处理1
    EXTJS4.2——8.Form+gride+linq进行前后端传输
    LINQ的实例
    高级委托使用
    C# 委托
  • 原文地址:https://www.cnblogs.com/smzd/p/11911434.html
Copyright © 2011-2022 走看看