Javascript 富文本编辑器,单击按钮后内容可编辑区域失去焦点

azu*_*nko 2 html javascript contenteditable

我有一个简单的 javascript 富文本编辑器,仅包含具有以下 onclick 的粗体按钮:

  document.execCommand('bold', false)
Run Code Online (Sandbox Code Playgroud)

和简单的html...

<div contenteditable="true">
Run Code Online (Sandbox Code Playgroud)

我的问题是,当我单击粗体按钮时,文本区域失去焦点,有什么解决方案吗?

epa*_*llo 5

好吧,焦点移到按钮上,因此您需要取消单击操作,以便焦点不会在内容可编辑元素中丢失。

document.querySelector(".actions").addEventListener("mousedown", function (e) {
  var action = e.target.dataset.action;
  if (action) {
    document.execCommand(action, false)
    //prevent button from actually getting focused
    e.preventDefault();
  }
})
Run Code Online (Sandbox Code Playgroud)
[contenteditable] {
  width: 300px;
  height: 300px;
  border: 1px solid black;
}
Run Code Online (Sandbox Code Playgroud)
<div class="actions">
  <button data-action="bold">bold</button>
  <button data-action="italic">italic</button>
</div>
<div contenteditable="true"></div>
Run Code Online (Sandbox Code Playgroud)