Javascript 在div中获取选定文本的html
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5669448/
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
get selected text's html in div
提问by Niraj Choubey
i have a div with contentEditable set to true. I have to find selected text html.I am able to get selected text in FireFox by
我有一个 contentEditable 设置为 true 的 div。我必须找到选定的文本 html。我可以通过以下方式在 FireFox 中获取选定的文本
window.getSelection();
I case of IE i am able to get selected text html by using
我在 IE 的情况下,我可以通过使用获得选定的文本 html
document.selection.createRange().
But, how can i find selected text html in FireFox. How can in do this.Please help.
但是,如何在 FireFox 中找到选定的文本 html。怎么能做到这一点。请帮忙。
回答by Tim Down
To get the selected HTML as a string, you can use the following function:
要将选定的 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;
}
回答by Hussein
Select text and store it in variable called mytext
.
选择文本并将其存储在名为mytext
.
if (!window.x) {
x = {};
}
x.Selector = {};
x.Selector.getSelected = function() {
var t = '';
if (window.getSelection) {
t = window.getSelection();
} else if (document.getSelection) {
t = document.getSelection();
} else if (document.selection) {
t = document.selection.createRange().text;
}
return t;
}
$(function() {
$(document).bind("mouseup", function() {
var mytext = x.Selector.getSelected();
alert(mytext);
});
});
Check working example at http://jsfiddle.net/YstZn/1/
在http://jsfiddle.net/YstZn/1/检查工作示例
回答by Zirak
window.getSelection().getRangeAt(0);
It returns a document fragment. It contains the nodes where the selection begins and ends and some other juicy stuff. Inspect it with FireBug or another JavaScript console, &&|| for more info
它返回一个文档片段。它包含选择开始和结束的节点以及其他一些有趣的东西。使用 FireBug 或其他 JavaScript 控制台检查它, &&|| 欲了解更多信息
回答by Naftali aka Neal
to get the text of a div you do this:(in jQuery)
要获取 div 的文本,您可以这样做:(在 jQuery 中)
var text = $('div.selector').text();