[英]Calling getBoundingClientRect() on element returns object with zero values
I have a simple ionic 5.31.1 / Angular 11.1.0 web app where I place a div (inner div) inside another div (outer div).我有一个简单的 ionic 5.31.1 / Angular 11.1.0 web 应用程序,我将一个 div(内部 div)放在另一个 div(外部 div)中。 I want to access the position of the inner div relative to the outer div from the code.我想从代码中访问相对于外部 div 的内部 div 的 position。 Calling getBoundingClientRect()
to the inner div returns an object where top
, bottom
, left
, right
, x
and y
are all 0
.调用getBoundingClientRect()
到内部 div 会返回一个 object ,其中top
、 bottom
、 left
、 right
、 x
和y
都是0
。
Here is the code这是代码
import { Component, AfterViewInit, ViewChild, ElementRef } from '@angular/core';
import { Platform } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import { DomController } from '@ionic/angular';
@Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.scss']
})
export class AppComponent implements AfterViewInit {
constructor(
private readonly platform: Platform,
private readonly splashScreen: SplashScreen,
private readonly statusBar: StatusBar,
private readonly domCtrl: DomController
) {
this.initializeApp();
}
@ViewChild('box')
private box: ElementRef;
initializeApp() {
this.platform.ready().then(() => {
this.statusBar.styleDefault();
this.splashScreen.hide();
});
}
async ngAfterViewInit() {
await this.domCtrl.read(() => {
console.log(this.box.nativeElement.getBoundingClientRect()); // <-- returns { top: 0, bottom: 0, ... }
});
}
}
<ion-app>
<div class="outer-box">
<div #box class="inner-box"></div>
</div>
</ion-app>
.outer-box {
background: yellow;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
}
.inner-box {
position: relative;
background: blue;
width: 50px; height: 50px;
}
Try using Angulars AfterContentChecked lifecycle since you are projecting your html to the component尝试使用 Angulars AfterContentChecked 生命周期,因为您将 html 投影到组件
ngAfterContentChecked() {
if (this.box) {
await this.domCtrl.read(() => {
console.log(this.box.nativeElement.getBoundingClientRect());
});
}
}
And just for a test try to add a setTimeout function inside the life cycle hook and only then getBoundingClientRect(), perhaps the element havent been fully rendered when you are checking it只是为了测试尝试在生命周期钩子中添加一个setTimeout function,然后才getBoundingClientRect(),也许当你检查它时元素还没有完全呈现
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.