MutationObserver监听DOM变化示例
示例代码:
<template>
<div class="it-bottom-button" :style="{ right: bottomBarRight }">
<slot></slot>
</div>
</template>
<script>
export default {
name: "itBottomBar",
componentNmame: "itBottomBar",
props: {
el: {
type: String,
default: "#subview"
},
right: {
type: String,
default: "20px"
}
},
data() {
return {
bottomBarScrollBarWidth: 0,
bottomBarRight: "20px",
mutationObserver: null
};
},
watch: {
right() {
this.bottomBarRight = this.right;
}
},
mounted() {
this.getScrollWidth();
this.initMutationObserver();
},
beforeDestroy() {
// 停止监控
this.mutationObserver.disconnect();
this.mutationObserver = null;
},
methods: {
getScrollWidth() {
const outer = document.createElement("div");
outer.className = "el-scrollbar__wrap";
outer.style.visibility = "hidden";
outer.style.width = "100px";
outer.style.position = "absolute";
outer.style.top = "-9999px";
document.body.appendChild(outer);
const widthNoScroll = outer.offsetWidth;
outer.style.overflow = "scroll";
const inner = document.createElement("div");
inner.style.width = "100%";
outer.appendChild(inner);
const widthWithScroll = inner.offsetWidth;
outer.parentNode.removeChild(outer);
this.bottomBarScrollBarWidth = widthNoScroll - widthWithScroll;
},
// 初始化MutationObserver监听DOM变化
initMutationObserver() {
const MutationObserver = window.MutationObserver || window.WebkitMutationObserver || window.MozMutationObserver;
// 监测浏览器是否支持
const observeMutationSupport = !!MutationObserver;
if (!observeMutationSupport) return;
const subview = document.querySelector(this.el);
const config = {
attributes: true,
childList: true,
characterData: true,
subtree: true
};
this.mutationObserver = new MutationObserver(() => {
this.bottomBarViewChange();
});
this.mutationObserver.observe(subview, config);
},
bottomBarViewChange() {
const subview = document.querySelector(this.el);
let subviewScrollHeight = subview.scrollHeight; // 内容高度
let subvviewOffsetHeight = subview.offsetHeight; // 可视区域高度
if (subviewScrollHeight > subvviewOffsetHeight) {
this.bottomBarRight = this.bottomBarScrollBarWidth + Number(this.right.replace("px", "")) + "px";
} else {
this.bottomBarRight = this.right;
}
}
}
};
</script>
使用示例:
<it-bottom-bar>
<el-button @click="goBack">取 消</el-button>
<el-button type="primary" @click="submitForm('ruleForm')">保 存</el-button>
</it-bottom-bar>
+
(^_^)打赏作者喝个咖啡(^_^)


我要收藏
返回顶部
跳到底部
分类:
JS
标签:
MutationObserver
, 监听DOM变化
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
2021-09-13 JavaScript之Blob对象基本用法及分片上传示例
2017-09-13 JS之document.cookie详解以及$.cookie的使用
2017-09-13 CSS3 calc实现滚动条出现页面不跳动
2015-09-13 CSS属性disabled和readonly的区别是什么
2015-09-13 CSS之Normalize.css的使用(重置表)
2015-09-13 CSS reset重置样式有那么重要吗?