Return HTML from a user-selected text

那年仲夏 提交于 2019-11-26 17:27:07

Here's a function that will get you HTML corresponding to the current selection in all major browsers:

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());
Christian Joudrey

Use Rangy: https://github.com/timdown/rangy

Cross-browser range and selection library.

Check out the demos here: http://rangy.googlecode.com/svn/trunk/demos/index.html

Alert boxes do not display HTML, just plain text. You can't get the HTML to show in an alert box.

What you can do is use some JS alert box replacement instead of alert, such as jQuery Dialog, a jQuery plugin, or something else entirely.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!