javascript - 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);
}
});
}
}
```
解决方案
我不确定你是否想简单地使用 .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中看到
推荐阅读
- android - 如何在 Android 上阻止或隐藏应用程序访问?
- java - 将 JSON 写入/更新到 URL (www.myjson.com)
- serverless - 使用 serverless.yml 为 dynamoDB 自定义 dynamoDB 模型嵌套结构
- ios - Stripe iOS 更改返回按钮标题
- java - 如何从 Java 中的 SSH DSA 公钥计算指纹?
- javascript - 几乎相同的代码,不同的输出。JavaScript 在这里有什么不同?
- ssh - 如何只通过ssh转发端口,不进入远程提示?
- java - 通过 OTP 重置密码
- java - 查找时差较大的行并将这些行复制到新列
- javascript - Gremlin Javascript 折叠、合并和展开