简体   繁体   中英

Detect click outside textarea

When the user enters text in my textarea, my window changes color. I want that when it clicks outside the textarea, it replaces color as before.

<textarea class="chat-input"
              id="textarea"
              rows="2" cols="50"
              (keyup)="detectTextarea($event)">
</textarea>


detectTextarea(event: any): any {
   this.changeColor = true;
   var textarea = document.getElementById("textarea");
}

/////////UPDATE//////////// It does not work :

detectTextarea(event: any): any {
  var textarea = document.getElementById("textarea");

  textarea.addEventListener("focus", function( event ) {
    this.changeColor = true;
  }, true);
  textarea.addEventListener("blur", function( event ) {
    this.changeColor = false;
  }, true);
}

Change it like this:

<textarea class="chat-input"
    id="textarea"
    rows="2" cols="50"
    (focus)="func()"
    (blur)="otherFunc()"
    (keyup)="detectTextarea($event)">
</textarea>

and then:

func() {
    this.changeColor = true;
  }
  otherFunc() {
    this.changeColor = false;
  }
}

您可以收听blur事件,以了解用户何时退出文本区域。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM