如何在div
<{1}} html
中查找所选文字
例如,我们在本文中选择了5到11:
<div id="txt" >This is some <i> text </i> </div>
已选中:is some
,
但在html
中是:id="txt
如何查找并在<p>
或<span>
之间替换其他标签以避免丢失?
请原谅我糟糕的英语:)
答案 0 :(得分:1)
演示: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);
}
取自:How to replace selected text with html in a contenteditable element?
在你问之前先试着找东西;]