選択状態のテキストを扱う

Rangeオブジェクト

  • 選択範囲を扱うには、Rangeオブジェクトを使う。
  • IEとそれ以外のブラウザでRangeオブジェクト取得方法が違うので、処理を分岐する。
    • IE:Rangeオブジェクトを作成する。
    • それ以外のブラウザ:SelectionオブジェクトからRangeオブジェクトを取り出す。

サンプル

以下の機能を持つ。

  • show() 選択状態の文字列を取り出す
  • surround() 選択状態の文字列をタグで囲む
 <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>

参考


トップ   編集 凍結 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS

Last-modified: 2009-11-10 (火) 16:32:27