我有一个 contentEditable 设置为 true 的 div。我必须找到选定的文本 html。我可以通过以下方式在 FireFox 中获得选定的文本
window.getSelection();
我在 IE 的情况下,我可以使用
document.selection.createRange().
但是,如何在 FireFox 中找到选定的文本 html。怎么能做到这一点。请帮忙。
我有一个 contentEditable 设置为 true 的 div。我必须找到选定的文本 html。我可以通过以下方式在 FireFox 中获得选定的文本
window.getSelection();
我在 IE 的情况下,我可以使用
document.selection.createRange().
但是,如何在 FireFox 中找到选定的文本 html。怎么能做到这一点。请帮忙。
要将选定的 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;
}
选择文本并将其存储在名为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);
});
});
window.getSelection().getRangeAt(0);
它返回一个文档片段。它包含选择开始和结束的节点以及其他一些有趣的东西。使用 FireBug 或其他 JavaScript 控制台检查它, &&|| 欲了解更多信息
根据 MDN:
“一个 Selection 对象,当转换为字符串时,通过附加一个空字符串 ("") 或使用 Selection.toString(),返回选定的文本。”
对我来说,以下任何一项在 Chrome 86 中都有效:
String(window.getSelection())
window.getSelection() + ""
window.getSelection().toString()
String(document.getSelection())
document.getSelection() + ""
document.getSelection().toString()
https://developer.mozilla.org/en-US/docs/Web/API/Window/getSelection
要获取 div 的文本,您可以这样做:(在 jQuery 中)
var text = $('div.selector').text();