Angular 9+中clientWidth始终返回0:获取图片宽高失败求助
解决Angular指令中clientWidth返回0的问题
我来帮你排查下这个问题~你的指令里ngAfterViewInit执行时,虽然DOM结构已经渲染好了,但图片资源可能还没加载完成,这时候元素的clientWidth和clientHeight自然会返回0。下面给你几个可行的解决方案:
方案1:监听图片的load事件
图片只有完全加载完成后,才会有实际的宽高值。我们可以给图片绑定load事件,在事件触发时再执行你的适配逻辑:
import { Directive, ElementRef } from '@angular/core'; import { fromEvent } from 'rxjs'; import { take } from 'rxjs/operators'; @Directive({ selector: '[image-fit]' }) export class ImageFitDirective { constructor(private _elementRef: ElementRef) { } ngAfterViewInit(): void { this._setupImageLoadListener(); } private _setupImageLoadListener(): void { const imgElement = this._elementRef.nativeElement as HTMLImageElement; // 处理图片从缓存加载的情况(此时load事件不会触发) if (imgElement.complete) { this._fit(); return; } // 监听一次load事件,避免重复触发 fromEvent(imgElement, 'load') .pipe(take(1)) .subscribe(() => { this._fit(); }); } private _fit(): void { const width = this._elementRef.nativeElement.clientWidth; const height = this._elementRef.nativeElement.clientHeight; console.log(width, height); // 在这里添加你的图片适配逻辑 } }
方案2:适配动态变化的图片src
如果你的图片src是通过[src]动态绑定的(比如从接口获取后赋值),那ngAfterViewInit执行时可能src还没设置,这时候需要监听src的变化,再绑定load事件:
import { Directive, ElementRef, Input, OnChanges, SimpleChanges } from '@angular/core'; @Directive({ selector: '[image-fit]' }) export class ImageFitDirective implements OnChanges { @Input() src!: string; constructor(private _elementRef: ElementRef) { } ngOnChanges(changes: SimpleChanges): void { // 当src发生变化且有有效值时,重新监听加载事件 if (changes['src'] && changes['src'].currentValue) { this._setupImageLoadListener(); } } private _setupImageLoadListener(): void { const imgElement = this._elementRef.nativeElement as HTMLImageElement; imgElement.onload = () => { this._fit(); }; // 处理缓存加载的情况 if (imgElement.complete) { this._fit(); } } private _fit(): void { const width = this._elementRef.nativeElement.clientWidth; const height = this._elementRef.nativeElement.clientHeight; console.log(width, height); } }
额外注意点
如果以上方法还是返回0,你可以检查这两个情况:
- 图片或其父元素是否设置了
display: none,这种情况下元素的宽高会被计算为0; - 是否有CSS样式(比如
opacity: 0、visibility: hidden)虽然视觉上不可见,但不影响宽高计算,这种情况可以正常获取值,但如果是display: none就不行。
内容的提问来源于stack exchange,提问作者Val Do
相关产品推荐
相关产品推荐

