我有一个简单的 javascript 富文本编辑器,仅包含具有以下 onclick 的粗体按钮:
document.execCommand('bold', false)
和简单的 html...
<div contenteditable="true">
我的问题是,当我点击粗体按钮时,文本区域失去了焦点,有什么解决办法吗?
最佳答案
好吧,焦点移到了按钮上,因此您需要取消单击操作,这样焦点才不会丢失在内容可编辑元素中。
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();
}
})
[contenteditable] {
width: 300px;
height: 300px;
border: 1px solid black;
}
<div class="actions">
<button data-action="bold">bold</button>
<button data-action="italic">italic</button>
</div>
<div contenteditable="true"></div>
关于Javascript富文本编辑器,单击按钮后内容可编辑区域失去焦点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46057207/