Chrome没有't获取选定的html字符串包装标记(contenteditable)

Chrome doesn't get the selected html string wrapping tags (contenteditable)

本文关键字:包装 字符串 html contenteditable 没有 获取 Chrome      更新时间:2023-09-26

我使用Tim Down的这个解决方案在一个可编辑内容的div中获取选定的html,它运行良好(谢谢Tim!)但是使用Chrome,如果我在html标签的边界处选择一个html字符串,如下图所示:https://i.stack.imgur.com/tBqlf.png:

我得到的只是纯文本(在本例中为test)。

如果将所选内容扩展到下一个字符(例如字母c),则会得到正确的html(<strong>test</strong> c)。

我可以通过在图片中选择一个类似的单词来获得Webkit中的完整html吗?感谢

不是。WebKit在将任何范围的每个边界添加到选择中时都会对其进行规范化,以使其符合WebKit关于文档中有效选择/插入符号位置的想法。您可以更改原始函数,使其检测包含元素内所有文本的选择的大小写,并扩展选择范围以包围该元素(而无需实际更改选择)。这里有一个简单的例子(对于更一般的情况,您可能需要更聪明的东西,例如当文本位于嵌套元素内时,检测块/内联元素等):

演示:http://jsfiddle.net/btLeg/

代码:

function adjustRange(range) {
    range = range.cloneRange();
    // Expand range to encompass complete element if element's text
    // is completely selected by the range
    var container = range.commonAncestorContainer;
    var parentElement = container.nodeType == 3 ?
            container.parentNode : container;
    if (parentElement.textContent == range.toString()) {
        range.selectNode(parentElement);
    }
    return range;
}
function getSelectionHtml() {
    var html = "", sel, range;
    if (typeof window.getSelection != "undefined") {
        sel = window.getSelection();
        if (sel.rangeCount) {
            var container = document.createElement("div");
            for (var i = 0, len = sel.rangeCount; i < len; ++i) {
                range = adjustRange( sel.getRangeAt(i) );
                container.appendChild(range.cloneContents());
            }
            html = container.innerHTML;
        }
    } else if (typeof document.selection != "undefined") {
        if (document.selection.type == "Text") {
            html = document.selection.createRange().htmlText;
        }
    }
    return html;
}