javascript 从用户选择的文本返回 HTML
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4652734/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Return HTML from a user-selected text
提问by Cruinh
I have the following, very simple html page:
我有以下非常简单的 html 页面:
<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.".
当我选择整个第一行并将鼠标悬停在方块上时,我会收到一条警告“这是文本。”。
How would I fix this so the the span tag or any other selected HTML isn't stripped out of the alert message?
我将如何解决这个问题,以便 span 标记或任何其他选定的 HTML 不会从警报消息中删除?
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.
编辑:我正在专门寻找如何从window.getSelection(). 警报对话框正是我尝试验证代码的方式。我只关心在 Safari 中的这个工作。
回答by Tim Down
Here's a function that will get you HTML corresponding to the current selection in all major browsers:
这是一个函数,可以让您获得与所有主要浏览器中的当前选择相对应的 HTML:
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());
回答by Christian Joudrey
Use Rangy: https://github.com/timdown/rangy
使用 Rangy:https: //github.com/timdown/rangy
Cross-browser range and selection library.
跨浏览器范围和选择库。
Check out the demos here: http://rangy.googlecode.com/svn/trunk/demos/index.html
在此处查看演示:http: //rangy.googlecode.com/svn/trunk/demos/index.html
回答by Jon
Alert boxes do not display HTML, just plain text. You can't get the HTML to show in an alert box.
警报框不显示 HTML,只显示纯文本。您无法让 HTML 显示在警告框中。
What you cando is use some JS alert box replacement instead of alert, such as jQuery Dialog, a jQuery plugin, or something else entirely.
您可以做的是使用一些 JS 警报框替换来代替alert,例如jQuery Dialog、jQuery 插件或其他完全不同的东西。

