获取内容高度
getNewsHieght(index) {
uni.createSelectorQuery().select(`.content_${index}`).boundingClientRect(rect => {
console.log('打印该盒子的元素', rect.height);
swiperHeight.value = rect.height
// console.log('打印swiperHeight的数值',this.swiperHeight);
}).exec()
}
H5配合 MutationObserver 监听 DOM 变化
MutationObserver 是监听 DOM 变化的更精准方案,适合动态列表渲染的场景
function watchHeight(){
const targetNode = document.getElementsByClassName(`content_0`)[0];
console.log(targetNode);
const observer = new MutationObserver((mutationsList, observer) => {
for (const mutation of mutationsList) {
if (mutation.type === 'childList') {
getNewsHieght(0)
// 停止观察(如果只需要执行一次)
observer.disconnect();
}
}
});
observer.observe(targetNode, {
childList: true, // 监听子节点的变化
subtree: false, // 不监听后代节点
});
}
获取高度后赋值到指定的元素上,多用于设置swiper高度