如何在contenteditable元素中用html替换所选文本? [英] How to replace selected text with html in a contenteditable element?
本文介绍了如何在contenteditable元素中用html替换所选文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用contenteditable元素,如何用我自己的html替换所选内容?
With a contenteditable element how can I replace the selected content with my own html?
推荐答案
在此处查看工作jsFiddle: http://jsfiddle.net/dKaJ3/2/
See here for working jsFiddle: http://jsfiddle.net/dKaJ3/2/
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;
}
}
alert(html);
}
代码取自 Tim Down :从用户选择的文本中返回HTML
这篇关于如何在contenteditable元素中用html替换所选文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文