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

时间:2017-09-05 14:15:58

标签: javascript html contenteditable

我有简单的javascript富文本编辑器,只包含以下onLlick的粗体按钮:

  document.execCommand('bold', false)

简单的HTML ......

<div contenteditable="true">

我的问题是,当我点击粗体按钮时,文本区域失去了它的焦点,是否有一些解决方案呢?

2 个答案:

答案 0 :(得分:4)

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

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>

答案 1 :(得分:1)

答案更新

看看this answer,您可以保存并恢复当前的满意位置,将模糊事件监听器添加到您满意的

一个例子:

&#13;
&#13;
//
// restore position after click
//
document.getElementById('btn').addEventListener('click', function(e) {
    restoreSelection(cpos);
})
//
// save position on blur
//
document.querySelector('div[contenteditable="true"]').addEventListener('blur', function(e) {
    cpos = saveSelection();
})



function saveSelection() {
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            return sel.getRangeAt(0);
        }
    } else if (document.selection && document.selection.createRange) {
        return document.selection.createRange();
    }
    return null;
}

function restoreSelection(range) {
    if (range) {
        if (window.getSelection) {
            sel = window.getSelection();
            sel.removeAllRanges();
            sel.addRange(range);
        } else if (document.selection && range.select) {
            range.select();
        }
    }
}
var cpos = -1;
&#13;
<button id="btn">Make bold</button>
<div contenteditable="true">
    this is the text
</div>
&#13;
&#13;
&#13;