Javascript:store and restore selection text
728x15 ad here
出自Guoshuang Wiki
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Storing and restoring text selection in Mozilla and in
MSIE/Win</title>
<script type="text/javascript">
var selection1, selection2;
function storeCurrentSelection () {
if (window.getSelection) {
var selection = window.getSelection();
if (selection.rangeCount > 0) {
var selectedRange = selection.getRangeAt(0);
return selectedRange.cloneRange();
}
else {
return null;
}
}
else if (document.selection) {
var selection = document.selection;
if (selection.type.toLowerCase() == 'text') {
return selection.createRange().getBookmark();
}
else {
return null;
}
}
else {
return null;
}
}
function restoreSelection (storedSelection) {
if (storedSelection) {
if (window.getSelection) {
var selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(storedSelection);
}
else if (document.selection && document.body.createTextRange) {
var range = document.body.createTextRange();
range.moveToBookmark(storedSelection);
range.select();
}
}
}
</script>
</head>
<body>
<h1>Storing and restoring text selection in Mozilla and in MSIE/Win</h1>
<p>You can select text in this page and then store the selection:
<input type="button" value="store current selection"
onclick="window.selection1 = storeCurrentSelection();">
</p>
<p>And here you can store a second selection:
<input type="button" value="store current selection"
onclick="window.selection2 = storeCurrentSelection();">
</p>
<p>Here you can restore the save selection:
<input type="button" value="restore first selection"
onclick="restoreSelection(selection1);">
<input type="button" value="restore second selection"
onclick="restoreSelection(selection2);">
</p>
</body>
</html>
