Here's a function that will get you HTML corresponding to the current selection in all major browsers. It also handles multiple ranges within a selection (currently only implemented in Firefox):
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;
}
alert(getSelectionHtml());
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…