更改 textarea 中唯一的单词 style/color?不 DIV

Change style/color of a only word in textarea? NOT DIV

这可能很荒谬。但是我正在逐步按照一些教程代码在发短信时更改 textarea 框的颜色,并且工作正常(在编写时将文本更改为大写和红色),但我只想更改一个单词。在另一个问题中,他们使用 div 标签元素,但我想使用 textarea 标签元素。谁能指出我正确的方向?

所以,这是代码:

document.getElementById("text").addEventListener("keypress", colors);

function colors() {
  var x = document.getElementById("text");
  var word = document.getElementById("text").value;
  x.value = x.value.toUpperCase();
  x.style.color = "red";
  
}
<textarea name="text" id="text">Some text</textarea>

你真的不能用文本区域来做到这一点。幸运的是,您可以使用 div 来模拟文本区域,这样您仍然可以通过将 contenteditable="true" 添加到标签

来在其中进行编辑

https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Editable_content

您可以为每个单词创建一个 <textarea> 元素,使用 if 条件和 colors 函数在 style 属性中设置特定的 color <textarea> 元素 .value.

textarea {
  border: none;
  outline: none;
  font-size: 14px;
  width: 50px;
  height: 16px;
  resize: none;
  overflow: hidden;
  margin: 0px;
  padding: 0px;
}
<textarea name="text1" class="text">Hello </textarea><textarea name="text2" class="text">World</textarea>
<script>
  var textareas = document.querySelectorAll("textarea");

  for (var i = 0; i < textareas.length; i++) {
    textareas[i].addEventListener("keypress", colors);
  }

  function colors() {
    if (this.value.indexOf("World") > -1) {
      this.value = this.value.toUpperCase();
      this.style.color = "red";
    }
  }
</script>