【问题标题】:offsetHeight and scrollHeight comparision works only inside setTimeout in Angular directiveoffsetHeight 和 scrollHeight 比较仅适用于 Angular 指令中的 setTimeout
【发布时间】:2021-03-09 07:29:31
【问题描述】:

我需要检查 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);
      }
    });
  }
}

```

【问题讨论】:

  • 如果不添加setTimeout会怎样?您可以将此行为添加到您的问题中吗
  • 我猜你需要一个滚动事件,添加带有滚动事件的 HostListener 并检测其中的滚动高度和偏移高度
  • 以下是图片中的一些示例。问题是当我在全尺寸桌面屏幕上打开页面时,橙色显示更多按钮不会出现在文本下方,即使文本的高度大于主机的高度。如果我在响应视图中打开我的条件工作很好。

标签: javascript html angular dom angular2-directives


【解决方案1】:

我不确定您是否只想使用 .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看到

【讨论】:

    猜你喜欢
    • 2014-05-05
    • 1970-01-01
    • 2023-04-02
    • 2017-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-11
    • 1970-01-01
    相关资源
    最近更新 更多