从用户选择的文本返回HTML [英] Return HTML from a user-selected text
问题描述
我有以下非常简单的html页面:
I have the following, very simple html page:
<html>
<head>
<script type="text/javascript">
function alertSelection()
{
var selection = window.getSelection();
var txt = selection.toString();
alert(txt);
}
</script>
</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>
当我选择整个第一行并将鼠标悬停在方块上时,我收到一条警告这是文本。。
When I select the entire first line and mouseover the square, I get an alert with "This is the text.".
我如何解决此问题,以便不会从警报消息中删除span标记或任何其他选定的HTML?
How would I fix this so the the span tag or any other selected HTML isn't stripped out of the alert message?
编辑:我正在专门研究如何从 window.getSelection()
获取完整的HTML。警报对话框就是我试图验证代码的方式。我只关心在Safari中工作。
edit: I'm looking specifically for how to get the full HTML from window.getSelection()
. The alert dialog was just how I was attempting to validate the code. I'm only concerned about this working in Safari.
推荐答案
这是一个能够获得与当前选择相对应的HTML的函数所有主流浏览器:
Here's a function that will get you HTML corresponding to the current selection in all major browsers:
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());
这篇关于从用户选择的文本返回HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!