文章目录
实时监听元素样式的变化
概述
参考文章: https://www.cnblogs.com/ygunoil/p/14299195.html
官方文档: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver/observe
注意: 必须配置、必须配置、必须配置:subtree=true以及characterData=true
MutationObserver监听选项
选项 | 值 | 作用 |
---|---|---|
childList | true/false | 设置为true表示监听指定元素的子元素的变动 |
attributes | true/false | 设置为true表示监听指定元素的属性的变动 |
characterData | true/false | 设置为true表示监听指定元素的data变动 |
subtree | true/false | 设置为true表示不紧监听目标元素也同时监听其子元素变动,不能单独设置此选项,必须至少包含前三个选项中的一个 |
attributeOldValue | true/false | 在attributes属性已经设为true的前提下,设置为true则会记录节点旧的属性值到MutationRecord的recordOldValue属性 |
characterDataOldValue | true/false | 在characterData属性已经设为true的前提下,设置为true则会记录节点旧的数据到MutationRecord的recordOldValue属性 |
attributeFilter | 监听的属性数组,比如[‘style’…] | 配置监听数组内的属性变化,数组外的属性变化会被忽略 |
代码
代码
data() {
return {
//侧边栏是否不展开
isCollapse: true,
menuDatas:menuDatas,
webSiteFooterInfoVO: {
},
recordOldValue: {
},
observer: null
}
},
methods: {
changeStyle: function () {
let MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver
let element = $("html").get(0)
this.observer = new MutationObserver((mutationList) => {
let width = str2Num(getComputedStyle(element).getPropertyValue('width'));
let height = str2Num(getComputedStyle(element).getPropertyValue('height'));
if (width === this.recordOldValue.width && height === this.recordOldValue.height) {
return
}
log("html元素尺寸发生变化:", this.recordOldValue, {width,height})
this.recordOldValue = {
width,
height
}
this.$nextTick(() => {
if(window.innerHeight > $("html").height()) {
$(".footerBox").addClass("outerWindowHeight");
}else {
$(".footerBox").removeClass("outerWindowHeight");
}
})
})
this.observer.observe(element, { attributes: true, subtree:true,characterData:true, attributeFilter: ['style'], attributeOldValue: true })
}
},
mounted: async function () {
//监听html元素的变化
this.changeStyle()
}