js 监听所有子节点的最大高度

发布时间 2023-09-12 20:31:32作者: 吃饭七分饱

// 目标节点
var targetNode = document.getElementById('target');

// 创建一个MutationObserver实例
var observer = new MutationObserver(function(mutationsList, observer) {
// 遍历所有的变动
for(var mutation of mutationsList) {
// 检查是否有子节点的高度发生了变化
if (mutation.type === 'childList') {
var maxHeight = 0;
// 遍历所有子节点
targetNode.childNodes.forEach(function(node) {
// 获取每个子节点的高度
var height = node.offsetHeight;
// 更新最大高度
if (height > maxHeight) {
maxHeight = height;
}
});
// 输出最大高度
console.log('Max Height: ' + maxHeight);
}
}
});

// 配置观察选项
var config = { childList: true, subtree: true };

// 开始观察目标节点
observer.observe(targetNode, config);