通过Javascript在浏览器中获取选定的HTML [英] Get Selected HTML in browser via Javascript
问题描述
我要求我的网络应用允许用户仅限打印。换句话说,用户选择文本和可能的图像,然后单击此选项。我已经看到了使用Javascript获取所选文本的示例,但是没有找到获取所选html本身的解决方案。
I have a requirement for my web app to allow the user to "Print Selected Only". In other words, a user selects text and potentially images and then clicks this option. I've seen examples of getting selected text with Javascript, but haven't found a solution for getting the selected html itself.
例如,如果我有这样的文件:
As an example if I have a document like so:
<html>
<head>
</head>
<body>
<p>A bunch of text</p>
<img src="someimage.jpg" />
<p>Even more text</p>
</body>
</html>
如果用户突出显示图像和第二段,我希望javascript返回:
If user highlights the image and the second paragraph, I'd want the javascript to return:
<img src="someimage.jpg" />
<p>Even more text</p>
这是可能的,怎么会这样做?
Is this possible and how would one go about doing it?
编辑:我最终选择了一个名为 Rangy 的js库。
I ended up going with a js library called Rangy for this.
推荐答案
以下是我在某处找到的一些代码,但我丢失了实际的链接,这似乎有效。
Here is some code I found somewhere but I lost the actual link and this seems to work.
<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>
代码存在一些问题(我测试过safari)它没有返回确切的选择。
There are some issues with the code (I tested with safari) where it doesn't return the exact selection.
这篇关于通过Javascript在浏览器中获取选定的HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!