javascript window.getSelection 返回 html

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5222814/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 16:25:41  来源:igfitidea点击:

window.getSelection return html

javascriptjqueryhtmldomexeccommand

提问by Zebra

function selected() {
   var selObj = window.getSelection();
}


This function returns selected text from a webpage. How do return the htmlof a selected area. Is this possible to do with an <img>and an <a>tag?


此函数从网页返回选定的文本。如何返回选定区域的html。这可能与一个<img>和一个<a>标签有关吗?


Here's the list of functions:
https://developer.mozilla.org/Special:Tags?tag=DOM&language=en


这是功能列表:https: //developer.mozilla.org/Special:
Tags?tag=DOM&language=en

回答by Tim Down

The following will do this in all major browsers and is an exact duplicate of this answer:

以下将在所有主要浏览器中执行此操作,并且与此答案完全相同:

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;
}