巧妙監(jiān)測(cè)元素尺寸變化

巧妙監(jiān)測(cè)元素尺寸變化----原文地址

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 監(jiān)聽(tīng) 變大變化
  // shrink 監(jiān)聽(tīng) 變小變化
  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)
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容