我要求我的网络应用程序允许用户"仅打印选择".换句话说,用户选择文本和可能的图像,然后单击此选项.我已经看到了使用Javascript获取所选文本的示例,但是没有找到获取所选html本身的解决方案.
举个例子,如果我有这样的文件:
<html>
<head>
</head>
<body>
<p>A bunch of text</p>
<img src="someimage.jpg" />
<p>Even more text</p>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
如果用户突出显示图像和第二段,我希望javascript返回:
<img src="someimage.jpg" />
<p>Even more text</p>
Run Code Online (Sandbox Code Playgroud)
这是可能的,如何去做呢?
编辑:我最终选择了一个名为Rangy的js库.
Sto*_*fke 34
这是我在某处找到的一些代码,但是我丢失了实际的链接,这似乎有效.
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>The serialized HTML of a selection in Mozilla and IE</title>
<script type="text/javascript">
function getHTMLOfSelection () {
var range;
if (document.selection && document.selection.createRange) {
range = document.selection.createRange();
return range.htmlText;
}
else if (window.getSelection) {
var selection = window.getSelection();
if (selection.rangeCount > 0) {
range = selection.getRangeAt(0);
var clonedSelection = range.cloneContents();
var div = document.createElement('div');
div.appendChild(clonedSelection);
return div.innerHTML;
}
else {
return '';
}
}
else {
return '';
}
}
</script>
</head>
<body>
<div>
<p>Some text to <span class="test">test</span> the selection on.
Kibology for <b>all</b><br />. All <i>for</i> Kibology.
</p>
</div>
<form action="">
<p>
<input type="button" value="show HTML of selection"
onclick="this.form.output.value = getHTMLOfSelection();">
</p>
<p>
<textarea name="output" rows="5" cols="80"></textarea>
</p>
</form>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
代码存在一些问题(我用safari测试过),它没有返回确切的选择.
类似的代码与其他实现具有相同的问题
http://snipplr.com/view/10912/get-html-of-selection/
getSelectionHTML = function () {
var userSelection;
if (window.getSelection) {
// W3C Ranges
userSelection = window.getSelection ();
// Get the range:
if (userSelection.getRangeAt)
var range = userSelection.getRangeAt (0);
else {
var range = document.createRange ();
range.setStart (userSelection.anchorNode, userSelection.anchorOffset);
range.setEnd (userSelection.focusNode, userSelection.focusOffset);
}
// And the HTML:
var clonedSelection = range.cloneContents ();
var div = document.createElement ('div');
div.appendChild (clonedSelection);
return div.innerHTML;
} else if (document.selection) {
// Explorer selection, return the HTML
userSelection = document.selection.createRange ();
return userSelection.htmlText;
} else {
return '';
}
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15293 次 |
| 最近记录: |