【问题标题】:Autosize textarea with max 5 line limit, then show scrollbar自动调整 textarea 最大 5 行限制,然后显示滚动条
【发布时间】:2020-01-18 01:57:37
【问题描述】:

说明:在 Angular 2 中,在我的聊天屏幕上,我想在输入时将聊天屏幕的大小增加到最多 5 行,然后显示滚动条。我该怎么做?

问题:行为不符合预期。此处需要滚动条限制为 5 行,理想情况下收缩,展开不起作用。

要求:它应该在我键入时扩展,在我按退格键时收缩。 5 行后它应该显示滚动条。

我的代码:

home.ts

autogrow(){
  let  textArea = document.getElementById("textarea")       
  textArea.style.overflow = 'hidden';
  textArea.style.height = '0px';
  textArea.style.height = textArea.scrollHeight + 'px';
}

home.html

<textarea id="textarea" (keyup)="autogrow()" ></textarea>

【问题讨论】:

  • 使用rows="{{rowSize}}" 属性。在你的功能内autogrow(){ rowSize++}
  • 如果你在 stackbiltz 上与你尝试过的任何东西共享最少的代码会更好,然后社区可以修复/修改你的代码并共享工作副本
  • @NajamUsSaqib 任何工作演示?
  • 查看这个例子:blog.invoiceberry.com/2011/03/…

标签: angular typescript ionic-framework ionic2 ionic3


【解决方案1】:

您可以尝试制作这样的指令:

    @Directive({
     selector: 'ion-textarea[autosize]'
     })

export class AutoSizeDirective implements OnInit {

  @HostListener('input', ['$event.target'])
  onInput(target): void {
    this.adjust(target);
  }

  @HostListener('focus', ['$event.target'])
  onFocus(target): void {
    this.adjust(target);
  }

  constructor(public element: ElementRef) {}

  ngOnInit(): void {
    setTimeout(() => this.adjust(), 100);
  }

  adjust(textArea: HTMLTextAreaElement = null): void {
    if (textArea == null) {
        textArea = this.element.nativeElement.getElementsByTagName('textarea')[0];
    }
    textArea.style.overflow = 'hidden';
    textArea.style.height = 'auto';
    textArea.rows = 1;

    if (textArea.scrollHeight < 200) { //or whatever height you like
      textArea.style.height = textArea.scrollHeight + 'px';
    } else {
      textArea.style.height = 200 + 'px';
    }

  }
}

然后在您的 html 中,您只需使用标签中的 autosize 属性,如下所示:

<textarea autosize .....>

您还必须将指令添加到 app.module 中。 希望这能解决您的问题。

【讨论】:

    猜你喜欢
    • 2022-10-13
    • 1970-01-01
    • 1970-01-01
    • 2021-11-25
    • 2015-07-25
    • 2011-09-22
    • 2021-12-09
    • 2015-08-26
    • 1970-01-01
    相关资源
    最近更新 更多