【问题标题】:Javascript rich text editor, contenteditable area loses focus after button is clickedJavascript富文本编辑器,点击按钮后内容可编辑区域失去焦点
【发布时间】:2017-09-05 14:15:57
【问题描述】:

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

  document.execCommand('bold', false)

还有简单的html...

<div contenteditable="true">

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

【问题讨论】:

  • 好吧,那是因为焦点移到了按钮上……取消动作。如果你显示你的点击事件,我可以告诉你一个解决方案。

标签: javascript html contenteditable


【解决方案1】:

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

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>

【讨论】:

  • 文本区域仍然失去焦点。
  • 大声笑,为什么对有效答案投反对票?这就是 OP 想要的,与其他答案不同
  • @Neal,嗯,不是我在 chrome 中测试它的时候。
  • 如果你愿意,我可以录下来吗? ;-)
  • 我也在使用 chrome(在 Mac 上)。
【解决方案2】:

答案更新

查看this answer,您可以保存和恢复当前的 contenteditable 位置,将 blur 事件侦听器添加到您的 contenteditable

一个例子:

//
// 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;
<button id="btn">Make bold</button>
<div contenteditable="true">
    this is the text
</div>

【讨论】:

  • 获得了 elemet 的焦点,但是它改变了光标的位置到不同的地方......
  • @azurinko 答案已更新。现在它应该可以工作了。告诉我
  • 是的,但是当您可以取消活动时有点矫枉过正。但是当它们在不点击按钮的情况下模糊时也可能很时髦
  • 为什么要投反对票?请至少留下评论。谢谢
  • 其实我可以用这个,不过不是问题的答案,谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-07-02
  • 1970-01-01
  • 2015-07-21
  • 2019-02-04
  • 1970-01-01
  • 2019-05-27
  • 1970-01-01
相关资源
最近更新 更多