1

我有以下代码用于获取用户选择文本的 html 代码。它在没有打开<span>标签的情况下完美运行。

function getHtml() {
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;
    }
}
alert(html); }

如果<span>用户选择的文本的代码中有一个打开标签,它会自动添加一个结束</span>标签。有解决这个问题的方法吗?

使用的 HTML 代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/2000/REC-xhtml1-20000126/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<SCRIPT LANGUAGE="JavaScript" SRC="HighlightedString.js">
</SCRIPT>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <title>Red and Louis</title>
    <link rel="stylesheet" media="screen" type="text/css" href="screen.css" />
    <link rel="stylesheet" media="print" type="text/css" href="other.css" />

</head>
<body onmouseup="getHtml()">
<div id="story">
<h1>Red and Louis</h1>

<p>Once upon a time in the middle of a large forest in Western Massachusetts, there lived a little girl who was about 14 years old and who loved baseball.  
<span style="font-family:Verdana, sans-serif; font-size:10pt">Text Within Span </span>
She thought that if she had grown up in the Midwest where there were hardly any trees, she would have been one of the best baseball players ever, but since she lived in the middle of a forest, there was no way for her to practice.  She had tried once but every ball had headed straight for the trees and though she thought they probably would have been homeruns, she couldn&rsquo;t tell for sure.</p>


</body>
</html>
4

2 回答 2

1

没有一种简单的方法可以得到你想要的。该函数为您返回内容的一种可能的 HTML 表示形式。它没有做的是将服务器返回的原始 HTML 的子字符串返回给浏​​览器。

在 IE < 9 以外的浏览器中,它会将所选内容的副本创建为 DOM DocumentFragment。为此,它必须通过仅复制部分选定节点的选定部分来创建节点树。正是这棵树被序列化回 HTML 字符串。

将克隆的选择内容与原始节点进行比较,并从输出中省略部分选择的节点的结束标签,可能会做一些复杂的事情,但我认为这样做没有什么大的收获。

于 2012-05-28T10:30:27.237 回答
0

您将所选文本转换为 html 并将其插入到元素中,这也将关闭所有打开的标签。

不确定您将其用于什么,但html = container.innerText;应该将其作为文本插入,并省略标签,如果这是您想要的?

于 2012-05-28T10:34:32.130 回答