我有一个 contentEditable 设置为 true 的 div。 我必须找到选定的文本 html。我可以通过
在 FireFox 中获取选定的文本 window.getSelection();
在 IE 的情况下,我可以通过使用获取选定的文本 html
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;
}
关于javascript - 在 div 中获取选定文本的 html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5669448/