Javascript 按钮在用户添加文本后停止写入文本区域

Javascript button ceases to write to texarea once user has added text

我正在尝试制作一个简单的文本编辑框,以便我最终可以 post 将文本发送到网站的另一部分。我正在尝试制作按钮以将文本设为粗体、斜体、添加代码框等(因此 insertAdjacentHTML 而不是 insertAdjacentText)但我决定开始确保我可以打印纯文本一个文本区域。 我很容易做到这一点,但现在我的问题是如何做到这一点,以便在用户向其添加文本后按钮仍然影响文本区域?下面的代码将愉快地输入 "hello",直到您单击文本区域,从那时起它拒绝输入,我不明白为什么。

window.hello = function(textarea) {
  var obj = document.getElementById("text");
  obj.insertAdjacentHTML('beforeend', 'hello');
}
<body>
  <button onclick="hello()">hello</button>
  <form>
    <p></p>
    <textarea id="text"></textarea>
  </form>
</body>

正如您从 MDN 中看到的,文本区域只能包含 字符数据.

这是因为您不能使用 insertAdjacentHTML 而是可以使用 .

如果您需要添加粗体文本或...您可以使用 contenteditable div 元素。

片段:

window.helloDiv = function() {
  var obj = document.getElementById("textDiv");
  obj.insertAdjacentHTML('beforeend', 'hello');
};
window.helloTxtArea = function() {
  var obj = document.getElementById("textTxtArea");
  obj.value += 'hello';
}
div {
  width: 300px;
  height: 100px;
  border: 1px;
  border-style: solid;
}

textarea {
  width: 300px;
  height: 100px;
  margin-top: 10px;
}
<button onclick="helloDiv()">helloDiv</button>
<button onclick="helloTxtArea()">helloTextArea</button>

<form>
    <p></p>
    <div id="textDiv" contenteditable="true"></div>
    <textarea id="textTxtArea" contenteditable="true"></textarea>
</form>