javascript - MutationObserver 未检测到高度变化
我有一个容器,里面有标题和主块,就像这样
<div #container class="container">
<div #header class="header">...</div>
<div class="main">
<lp-chart [chartHeight]="chartHeight"></lp-chart>
</div>
</div>
我的目标是检测 #header 高度的变化,并将高度设置到 #main 组件。所以你可以想象,
the whole #container is - 100%,
#header, for example, 50px,
and el inside #main block should be `100% - 50px`
一切几乎都正常工作,只是,在页面的左侧部分我有一个可以打开或折叠的侧边栏,所以窗口的大小不会改变,但头部会根据这个改变它的高度,
但是我的MutationObserver没有检测到它。
这个 detailsHeader 在 CSS 中将其高度设置为 max-height: 150px;,(所以当侧边栏折叠时,头部高度为 50px,如果展开 - 会扩展到 150),我认为这就是原因,但也可能我忽略了什么。这里是我的部分代码:service
setupHeightMutationObserver(el: ElementRef): Observable<HeightAndWidth> {
const observerable$ = new Observable<HeightAndWidth>(observer => {
const callback = () => observer.next(this.getHeightAndWidthObject(el));
const elementObserver = new MutationObserver(callback);
const config = { attributes: true, childList: true, subtree: true };
elementObserver.observe(el.nativeElement, config);
});
return observerable$
.pipe(
debounceTime(50),
distinctUntilChanged()
);
}
private getHeightAndWidthObject(el: ElementRef): HeightAndWidth {
const newValues = new HeightAndWidth();
newValues.height = el.nativeElement.getBoundingClientRect().height;
newValues.width = el.nativeElement.offsetWidth;
return newValues;
}
组件
@ViewChild('details') private details: ElementRef;
@ViewChild('detailsHeader') private detailsHeader: ElementRef;
ngAfterViewInit(): void {
this.subscription$ = this.elementResizeService.setupHeightMutationObserver(this.detailsHeader)
.subscribe((newValues: HeightAndWidth) => this.calculateChartSize(newValues));
}
calculateChartSize(newValues: HeightAndWidth): void {
const detailsHeader = this.elementResizeService.doDivHeightChange(newValues);
const detailsHeight = this.details.nativeElement.getBoundingClientRect().height;
const height = detailsHeight - detailsHeader.height - 10;
this.chartHeight = height;
}
ngOnDestroy(): void {
this.subscription$.unsubscribe();
}
答案#1
好吧,你明确说明你不能使用 resize Observer API。
另一种可能性是在 window 对象上附加一个 resize 事件。然后在此时读取你特定元素的尺寸。
此功能在 IE 中未经测试。但看起来自 IE4 起即可支持。
https://developer.mozilla.org/zh-CN/docs/Web/API/Window/resize_event
并且在此处作为片段效果不好(尝试调整大小、缩放、全屏,或调整控制台大小以触发 alert())。
注意使用了 % 和 vh CSS 单位,这无关紧要,这只是为了显示结果无论如何都是以像素为单位。
window.addEventListener("resize", getSizes, false)
function getSizes(){
let header = document.getElementById("header")
alert(header.clientWidth +"px x "+ header.clientHeight + "px")
}#header {
width: 100%;
height:12vh;
border: 3px black solid;
}<div id="header">
</div>
