在 contenteditable div 中用文本替换 HTML 时,有没有办法不丢失焦点选择?

Is there a way to not lose focus selection when replacing HTML with text in an contenteditable div?

我有一个可以编辑的 div 标签。

我不希望该标签中有任何 HTML,所以我不让用户输入任何内容。但是,当用户进行复制/粘贴时,包含标签的可能性不大。

我有一些 jQuery 代码来捕获 paste 事件,以防万一我尝试使用我的 saveSelection()restoreSelection() 函数,我在下面显示了哪些工作找到在很多情况下,但在这里他们失败了...

Fiddle: http://jsfiddle.net/9wm0oeah/2/

jQuery("#that_div").on("paste", function()
    {
        setTimeout(function()
            {
                // remove any HTML
                var selection = saveSelection();
                jQuery("#that_div").text(jQuery("#that_div").text());
                restoreSelection(selection);
            }, 0);
    });


function saveSelection()
{
    var sel;

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

function restoreSelection(range)
{
    var sel;

    if(document.selection)
    {
        range.select();
    }
    else
    {
        sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange((range));
    }
}

你知道它失败的原因吗?

当您更改可编辑 div 内的 DOM 节点时,div 内或部分存在的任何范围都必须更改以适应更改。如果您完全替换内容,就像您的代码所做的那样,范围边界相关的节点将被破坏,并且范围必须恢复为默认状态。

您可以改用基于字符偏移量的解决方案。例如:Can't restore selection after HTML modify, even if it's the same HTML