首页 > 编程知识 正文

利用 MutationObserver 监听 div 高度变化

时间:2023-05-03 09:38:32 阅读:284870 作者:1231

实现功能描述:

基于 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 介绍

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。