首页 > 解决方案 > offsetHeight 和 scrollHeight 比较仅适用于 Angular 指令中的 setTimeout

问题描述

我需要检查 Angular 指令中的 offsetHeight 是否低于 scrollHeight。问题是它只能像下面那样工作。我想避免使用 setTimeout。你能推荐我任何解决方法吗?提前致谢。

@Directive({
  selector: '[appEllipsisDirective]'
})
export class EllipsisDirective implements AfterViewInit {

 constructor(private ref: ElementRef) {
 }

  ngAfterViewInit() {
    setTimeout(() => {
      if (this.ref.nativeElement.offsetHeight < this.ref.nativeElement.scrollHeight) {
        this.init.emit(true);
      }
    });
  }
}

```

标签: javascripthtmlangulardomangular2-directives

解决方案


我不确定你是否想简单地使用 .css 来实现。如果你定义了一些像

.content
{
  display:flex;
  flex-wrap: nowrap;
  justify-content:space-between;
  align-items: flex-start;
  width:100%;
}
.line-clam
{
  display:block;
 overflow:hidden;
}

你可以有

    <div class="content">
        <div>
            <div class="line-clam" [style.max-height]="more?'80px':null">
                <span #text >Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua....</span>
            </div>
            <button *ngIf="text.offsetHeight>80" (click)="more=!more">
                 {{more?'more':'less'}}
            </button>
        </div>
        <button>one</button>
        <button>two</button>
    </div>

好吧,您可以在 ngOnInit 中添加对 window.resize 的订阅,以说 Angular 做出一些事情

  ngOnInit()
  {
   fromEvent(window, 'resize').pipe(debounceTime(1000)).subscribe();
  }

你可以在stackblitz中看到


推荐阅读