巧妙监测元素尺寸变化

巧妙监测元素尺寸变化----原文地址

public onelresize(el: HTMLElement, handler: Function) {
  if (!(el instanceof HTMLElement)) {
    throw new TypeError("Parameter 1 is not instance of 'HTMLElement'.")
  }
  // https://www.w3.org/TR/html/syntax.html#writing-html-documents-elements
  if (
    /^(area|base|br|col|embed|hr|img|input|keygen|link|menuitem|meta|param|source|track|wbr|script|style|textarea|title)$/i.test(el.tagName)
  ) {
    throw new TypeError(
      'Unsupported tag type. Change the tag or wrap it in a supported tag(e.g. div).'
    )
  }
  if (typeof handler !== 'function') {
    throw new TypeError("Parameter 2 is not of type 'function'.")
  }
  let lastWidth = el.offsetWidth || 1
  let lastHeight = el.offsetHeight || 1
  const maxWidth = 10000 * lastWidth
  const maxHeight = 10000 * lastHeight

  // expand 监听 变大变化
  // shrink 监听 变小变化
  const expand = document.createElement('div')

  //隐藏辅助子元素
  expand.style.cssText =
    'position:absolute;top:0;bottom:0;left:0;right:0;z-index=-10000;overflow:hidden;visibility:hidden;'
  const shrink = expand.cloneNode(false)

  const expandChild: HTMLElement = document.createElement('div')
  expandChild.style.cssText = 'transition:0s;animation:none;'
  const shrinkChild = expandChild.cloneNode(false)

  expandChild.style.width = maxWidth + 'px'
  expandChild.style.height = maxHeight + 'px'
  ;(shrinkChild as HTMLElement).style.width = '250%'
  ;(shrinkChild as HTMLElement).style.height = '250%'

  expand.appendChild(expandChild)
  shrink.appendChild(shrinkChild)
  el.appendChild(expand)
  el.appendChild(shrink)

  // 让 expand和shrink的父元素为el
  if (expand.offsetParent !== el) {
    el.style.position = 'relative'
  }

  expand.scrollTop = (shrink as HTMLElement).scrollTop = maxHeight
  expand.scrollLeft = (shrink as HTMLElement).scrollLeft = maxWidth

  let newWidth = 0
  let newHeight = 0

  function onScroll() {
    newWidth = el.offsetWidth || 1
    newHeight = el.offsetHeight || 1
    if (newWidth !== lastWidth || newHeight !== lastHeight) {
      requestAnimationFrame(onResize)
    }
    expand.scrollTop = (shrink as HTMLElement).scrollTop = maxHeight
    expand.scrollLeft = (shrink as HTMLElement).scrollLeft = maxWidth
  }

  function onResize() {
    if (newWidth !== lastWidth || newHeight !== lastHeight) {
      lastWidth = newWidth
      lastHeight = newHeight
      handler()
    }
  }

  expand.addEventListener('scroll', onScroll, false)
  shrink.addEventListener('scroll', onScroll, false)
}

你可能感兴趣的:(巧妙监测元素尺寸变化)