【发布时间】:2021-06-18 16:48:39
【问题描述】:
我有一个容器,里面有标题和主块,像这样
<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),我认为这就是原因,但也许我错过了一些东西。
这是我的代码的一部分:
服务
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();
}
【问题讨论】:
-
使用 resize Observer api 代替几何变化,见developer.mozilla.org/en-US/docs/Web/API/Resize_Observer_API
-
另外,不确定这是不是错字 -
<div #conteiner class="container"> -
@NVRM Resize Observer 在 IE 中不起作用,但不幸的是我的项目应该支持它
-
@wahwahwah 是的,这是一个错字……谢谢!
-
这真的很难说,因为你没有在 html 中包含你的侧边栏。想想你页面上的元素之间的关系以及你想要随着框架大小的变化而调整的东西......你的侧边栏是一个 child 元素吗?继承你不想要的 css?
标签: javascript html angular typescript