window.getSelection返回html [英] window.getSelection return html

查看:519
本文介绍了window.getSelection返回html的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



此功能从网页返回所选文字。如何返回所选区域的 html 。这可能与< img> < a> 标签有关?


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



这里是功能列表:

https://developer.mozilla.org/Special:Tags?tag=DOM&language=en

推荐答案

以下内容将在所有主流浏览器中进行,并且与这个答案

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

这篇关于window.getSelection返回html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆