Skip to content

Instantly share code, notes, and snippets.

@klb3713
Created June 27, 2013 13:59
Show Gist options
  • Save klb3713/5876641 to your computer and use it in GitHub Desktop.
Save klb3713/5876641 to your computer and use it in GitHub Desktop.
Javascript获取选中的html和取消选择状态代码,兼容IE、Chrome和FF
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;
}
function clearSelection(){
if (typeof window.getSelection != "undefined") {
window.getSelection().removeAllRanges();
} else if (typeof document.selection != "undefined") {
document.selection.empty();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment