use*_*494 37 javascript getselection
我可以使用以下代码来获取所选文本:
text=window.getSelection(); /// for Firefox
text=document.selection.createRange().text; /// for IE
但是如何获得所选的Html,其中包括text和html标签?
Tim*_*own 65
这是一个函数,它将为您提供与所有主流浏览器中当前选择相对应的HTML.它还处理选择中的多个范围(目前仅在Firefox中实现):
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());
Run Code Online (Sandbox Code Playgroud)
Mar*_*ahn 28
在IE <= 10个浏览器中,它是:
document.selection.createRange().htmlText
Run Code Online (Sandbox Code Playgroud)
正如@DarrenMB所指出的,IE11不再支持这一点.请参阅此答案以供参考.
在非IE浏览器中,我只是试着玩这个...这似乎有用,会有一些副作用,将节点分成两半并创建一个额外的跨度,但这是一个起点:
var range = window.getSelection().getRangeAt(0),
content = range.extractContents(),
span = document.createElement('SPAN');
span.appendChild(content);
var htmlContent = span.innerHTML;
range.insertNode(span);
alert(htmlContent);
Run Code Online (Sandbox Code Playgroud)
不幸的是,我似乎无法将节点恢复原状(例如,因为你可以从一个跨度中拉出一半的文本).
这就是我想出来的.经过IE,Chrome,Firefox,Safari,Opera测试.不返回空字符串.
function getSelected() {
var text = "";
if (window.getSelection
&& window.getSelection().toString()
&& $(window.getSelection()).attr('type') != "Caret") {
text = window.getSelection();
return text;
}
else if (document.getSelection
&& document.getSelection().toString()
&& $(document.getSelection()).attr('type') != "Caret") {
text = document.getSelection();
return text;
}
else {
var selection = document.selection && document.selection.createRange();
if (!(typeof selection === "undefined")
&& selection.text
&& selection.text.toString()) {
text = selection.text;
return text;
}
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
68453 次 |
| 最近记录: |