关于javascript:从用户选择的文本返回HTML

Return HTML from a user-selected text

我有以下非常简单的html页面:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<html>
    <head>
    <script type="text/javascript">
        function alertSelection()
        {
            var selection = window.getSelection();
            var txt = selection.toString();
            alert(txt);
        }
   
    </head>
    <body>
        This is <span style="background-color:black;color:white">the</span> text.
        <div style="background-color:green;width:30px;height:30px;margin:30px"
            onmouseover="alertSelection()">
    </body>
</html>

当我选择整个第一行并将鼠标悬停在正方形上时,会出现"这是文本"的警报。

我将如何解决此问题,以使span标记或任何其他选定的HTML不会从警报消息中剥离出来?

编辑:我正在专门寻找如何从window.getSelection()获取完整的HTML。 警报对话框正是我尝试验证代码的方式。 我只担心在Safari中工作。


这是一个可以在所有主要浏览器中为您提供与当前选择相对应的HTML的功能:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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());


使用Rangy:https://github.com/timdown/rangy

跨浏览器范围和选择库。

在此处查看演示:http://rangy.googlecode.com/svn/trunk/demos/index.html


警报框不显示HTML,而仅显示纯文本。 您无法使HTML显示在警报框中。

您可以做的是使用某些JS警报框替换而不是alert,例如jQuery Dialog,jQuery插件或其他完全替代的东西。