美文网首页
js 怎么监控一个普通DIV的宽高发生变化

js 怎么监控一个普通DIV的宽高发生变化

作者: IamaStupid | 来源:发表于2020-04-10 20:06 被阅读0次

情形:
左右两个div,有一个小按钮,点击时候,可以控制左边的div显示或隐藏,右边的div随着左边的div隐藏显示宽度会发生变化,里面的子级元素当然也会跟着变化。
但是因为特殊情况,必须要设置右边div里面的元素为absolute。
如果左边没隐藏,左边可以把最外面的div撑开(flex布局),右边也是有高度的。
但是如果左边隐藏了,右边因为内容脱出文档流,所以高度为0,内容看不到了。

现在我需要监听右边宽度变化,设置右边内容的高度。

代码:

mounted () {
    this.wrapDom = document.getElementById('tableWrap')
    let MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver
    let element = document.querySelector('#tableID')
    this.observer = new MutationObserver((objList) => {
      console.log('obj List:', objList)
      let width = element.offsetWidth
      if (this.recordOldValue && width === this.recordOldValue.width) {
        return
      }
      this.recordOldValue = {
        width
      }
      console.log('obj width:', width)
      this.wrapDom.style.height = element.offsetHeight + 58 + 'px'
    })
    this.observer.observe(element, { attributes: true, childList: true, subtree: true })
  },
  beforeDestroy () {
    // 停止观测
    this.observer.disconnect()
    this.observer = null
  }

https://developer.mozilla.org/zh-CN/docs/Web/API/MutationObserver
https://developer.mozilla.org/zh-CN/docs/Web/API/MutationObserverInit

相关文章

网友评论

      本文标题:js 怎么监控一个普通DIV的宽高发生变化

      本文链接:https://www.haomeiwen.com/subject/gcvdmhtx.html