在div中获取所选文本的html

Nir*_*bey 13 javascript jquery

我有一个div,其contentEditable设置为true.我必须找到所选的文本html.我能够在FireFox中获取所选文本

 window.getSelection();
Run Code Online (Sandbox Code Playgroud)

我的IE的情况我能够通过使用获得选定的文本html

document.selection.createRange().
Run Code Online (Sandbox Code Playgroud)

但是,我如何在FireFox中找到所选的文本html.怎么能这样做.请帮忙.

Tim*_*own 21

要将选定的HTML作为字符串,您可以使用以下函数:

function getSelectionHtml() {
    var html = "";
    if (typeof window.getSelection != "undefined") {
        var sel = window.getSelection();
        if (sel.rangeCount) {
            var container = document.createElement("div");
            for (var i = 0, len = sel.rangeCount; i < len; ++i) {
                container.appendChild(sel.getRangeAt(i).cloneContents());
            }
            html = container.innerHTML;
        }
    } else if (typeof document.selection != "undefined") {
        if (document.selection.type == "Text") {
            html = document.selection.createRange().htmlText;
        }
    }
    return html;
}
Run Code Online (Sandbox Code Playgroud)


Hus*_*ein 13

选择文本并将其存储在名为的变量中mytext.

if (!window.x) {
    x = {};
}
x.Selector = {};
x.Selector.getSelected = function() {
    var t = '';
    if (window.getSelection) {
        t = window.getSelection();
    } else if (document.getSelection) {
        t = document.getSelection();
    } else if (document.selection) {
        t = document.selection.createRange().text;
    }
    return t;
}

$(function() {
    $(document).bind("mouseup", function() {
        var mytext = x.Selector.getSelected();
        alert(mytext);
    });
});
Run Code Online (Sandbox Code Playgroud)

查看http://jsfiddle.net/YstZn/1/上的工作示例

  • `x.Selector.getSelected()`在大多数浏览器中返回一个`Selection`对象,在IE <= 8中包含一个包含所选文本的字符串.这些都不是选择的HTML,这是OP要求的. (4认同)