可以使用Javascript用鼠标获取用户选择的任何内容,例如:http://www.motyar.info/2010/02/get-user-selected-text-with-jquery-and.html

我的问题是,我不仅需要此文本,而且还需要:


以获得围绕此文本的html(例如,如果用户选择“ hello”,并且此hello在源中显示为:“ <div><span>hello</span></div>”,则该文本应返回)。
对图形做同样的事情


谁能指导我完成此过程,或者如果无法实现,还有其他替代方法吗?

最佳答案

这将在所有主流浏览器中完成。 IE和更符合标准的浏览器有单独的分支。在IE中,这稍微容易些,因为通过选择创建的专有TextRange对象具有方便的htmlText属性。在其他浏览器中,必须使用DOM Range的cloneContents()方法创建包含所选内容副本的DocumentFragment,并通过将片段附加到元素并返回元素的innerHTML属性来从中获取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;
}

alert(getSelectionHtml());

09-25 17:43