我有以下代码用于获取用户选择文本的 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’t tell for sure.</p>
</body>
</html>