我如何检测 scrollHeight
使用 MutationObserver
更改 DOM 元素?它不是属性,也不是数据。
背景:我需要检测滚动条何时出现在我的内容元素 overflow-y
上。其中设置为自动。我认为滚动条出现的瞬间 scrollHeight
的值从 0 跳到 500,所以想法是设置一个 MutationObserver
检测此属性的变化。
到目前为止我所得到的:
HTML
<div class="body" #body>
CSS
.body {
overflow-y: auto;
}
typescript
export class MyWatchedContent implements AfterViewInit, OnDestroy {
@ViewChild('body', { read: ElementRef })
private body: ElementRef;
private observer: MutationObserver;
public ngAfterViewInit() {
this.observer = new MutationObserver(this.observerChanges);
this.observer.observe(this.body.nativeElement, {
attributes: true,
});
}
public ngOnDestroy() {
this.observer.disconnect();
}
private observerChanges(records: MutationRecord[], observer: MutationObserver) {
console.log('##### MUTATION');
records.forEach((_record) => {
console.log(_record);
});
}
}
例如,如果我在开发人员窗口中更改背景颜色,我可以看到观察者正在触发
MUTATIONmy-content-watcher.component.ts?d0f4:233 MutationRecord {type: "attributes", target: div.body, addedNodes: NodeList(0), removedNodes: NodeList(0), previousSibling: null…}
但是,如果我更改窗口大小以显示滚动条,则不会检测到任何突变。这对
MutationObserver
是否可行?如果是这样,如何?
最佳答案
这是答案,对于仍在寻找解决方案的任何人:
截至今天,无法直接监控元素的 scrollHeight 变化 .
但解决方案非常接近:
解决方案
The ResizeObserver detects changes in the outer height of an element...
观察滚动容器没有意义,因为它的外部高度不会改变。改变它们的高度的元素是容器的任何 CHILD 节点!
一旦子节点的高度发生变化,就意味着父容器的scrollHeight发生了变化。
Vanilla JS版本
const container = document.querySelector('.scrollable-container');
const observer = new ResizeObserver(function() {
console.log('New scrollHeight', container.scrollHeight);
});
// This is the critical part: We observe the size of all children!
for (var i = 0; i < container.children.length; i++) {
observer.observe(container.children[i]);
})
jQuery 版本
const container = $('.scrollable-container');
const observer = new ResizeObserver(function() {
console.log('New scrollHeight', container[0].scrollHeight);
});
container.children().each(function(index, child) {
observer.observe(child);
});
进一步的步骤
当动态添加子项时,您可以添加 MutationObserver 以在添加新子项后将其添加到 ResizeObserver。
关于mutation-observers - 使用 MutationObserver 检测 scrollHeight 的变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44428370/