JavaScript 中监听 div 高度的变化

实现功能描述:

基于 vue + elementUI,在 Dialog 中有一个 Select 选择器,当 Select 的下拉列表显示时,要求高度能够撑开 Dialog。实现效果如图:
在这里插入图片描述

实现

实际项目代码结构稍微复杂,在这只说重点
A 组件伪代码:

<template>
  <div>
  ...

   <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      size="mini"
    >
      // 设置 div 的高度(重点)
      <div :style="{height: contHeight==='100%' ? '100%': contHeight+'px'}">
        <el-select
          clearable
          multiple
          // 重点
          @visible-change="handleVisible"
          placeholder="请输入内容"
        >
          <template v-slot:empty>
            // 设置这个 class="resource-tree" 这是下拉列表的最外层元素(重点)因为它的高度是不定的
            <div class="resource-tree">
              // 这是下拉树结构列表
              <el-tree></el-tree>
            </div>
          </template>
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
export default {
  name: 'A',
  props: {
  },
  data () {
    return {
    	contHeight: '100%',
    	observer: null
    }
  },
  computed: {
  },
  methods: {
    /**
     * 当触发某事件,显示 dialog 时,在该事件方法中监听 .resource-tree 元素
     * */
    showDialog () {
      this.dialogVisible = true
      this.$nextTick(() => {
        this.observer.observe(
          document.querySelector('.resource-tree'),
          // attributes: 监听属性变化  subtree:监听子元素变化
          { attributes: true, subtree: true }
        )
      })
    },
    
    /**
     * dialog 中下拉选择隐藏或显示触发
     * */
    handleVisible (flag) {
      if (flag) {
        this.computeHeight()
      } else {
        this.contHeight = '100%'
      }
    },
    
     /**
     * 计算 .resource-tree 元素高度
     * */
    computeHeight () {
      this.$nextTick(() => {
        // dom 元素加载完成后获取 .resource-tree 的 offsetHeight。加 80 是向下富裕多少像素,可改
        this.contHeight = document.querySelector('.resource-tree').offsetHeight + 80
      })
    },
  },
  watch: {
  },
  created () {
  },
  mounted () {
    /* 监听 .resource-tree 高度变化 */
    const MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver
    this.observer = new MutationObserver((list) => {
      // 当被监听的元素发生变化,会执行该方法
      this.computeHeight()
    })
  },
  beforeUpdate () {
  },
  updated () {
  },
  beforeDestroy () {
  }
}

主要是利用 MutationObserver ,对 dom 进行监听,dom 变化,动态计算 .resource-tree 的高度。
MutationObserver 介绍

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值