選択状態のテキストを扱うRangeオブジェクト
サンプル以下の機能を持つ。
<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; // range.textでテキストのみ取り出す } else { if (!window.getSelection().rangeCount) return; var range = window.getSelection().getRangeAt(0); var frag = range.cloneContents(); 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); } 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> 参考
|
|