選択状態のテキストを扱う
<html>
<head>
<script type='text/javascript' src='http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js'></script>
<script type="text/javascript">
var isIE = navigator.appName == 'Microsoft Internet Explorer' ? true : false;
var sample = {
init: function () {
document.getElementById('show').onclick = this.show;
document.getElementById('surround').onclick = this.surround;
},
// 選択状態の文字列を取り出す
show: function() {
var output;
if (isIE) {
var range = document.selection.createRange();
output = range.htmlText;
} else {
if (!window.getSelection().rangeCount) return;
var range = window.getSelection().getRangeAt(0);
var frag = range.cloneContents();
console.log(frag.firstChild.nodeValue);
output = frag.firstChild.nodeValue;
}
alert(output);
},
// 選択状態をタグ(文字列)で囲む
surround: function () {
var span = document.createElement("span");
span.style.color = "red";
if (isIE) {
var range = document.selection.createRange();
var container = document.createElement("");
container.appendChild(span);
span.innerHTML = range.htmlText;
range.pasteHTML(container.innerHTML);
console.dir(document.getElementById("dv"));
} else {
if (!window.getSelection().rangeCount) return;
var range = window.getSelection().getRangeAt(0);
range.surroundContents(span);
}
}
};
</script>
</head>
<body onload="sample.init()">
<div id="dv">abc 123 xyz</div>
<br /><input id="show" type="button" value="show">
<br /><input id="surround" type="button" value="surround">
</body>
</html>