April 19, 2007

javascriptでカーソル位置にタグを挿入

javascriptでテキストエリアの現在のカーソル位置に、タグを挿入する。
結構難しい(面倒)のかなと思ってたけど、以外と簡単。

ちょっと親切に、挿入後にカーソル位置をタグに挟まれた位置に移動してあげる。

IEとfoxとoperaで動作確認済み。
※ 最新のsafariなら動くかも

------------- test.html -------------------------

<html>
<body>

<select id="tagBox" onChange="tagInsert()">
  <option value="default"></option>
  <option value="<b></b>">太文字</option>
  <option value="<u></u>">下線</option>
  <option value="<s></s>">取消し線</option>
</select>

<textarea id="body"></textarea>

<script type="text/javascript">
function tagInsert()
{
  var tagBox = document.getElementById('tagBox');
  var insert = tagBox.value;
  if (insert == 'default') return;

  var tarea = document.getElementById('body');
  tarea.focus();

  if (/*@cc_on!@*/false) { // IE
    var sel = document.selection.createRange();
    sel.text = insert;
    var pos = Math.floor(insert.length / 2) + 1;
    sel.move('character', -pos);
    sel.select();
  } else {
    var body = tarea.value;
    var at   = tarea.selectionStart;
    var tmp  = body.substr(0, at);

    tarea.value = tmp + insert + body.substr(at, body.length);
    var cursor = Math.floor(insert.length / 2) + at;
    tarea.setSelectionRange(cursor, cursor);
  }

  tagBox.options[0].selected = true;
}
</script>

</body>
</html>

------------------------------------------------

今回はセレクトボックスで選んだタグを挿入してみた。
ボタンにして、少し頑張れば選択した文字列をタグで囲むというのもできそう。

まぁ、今回はこれで間に合うので、とりあえず。


-- 追記 --
http://jack1118.livedoor.biz/archives/2007-06.html#20070602 も参考に。


トラックバックURL

コメントする

名前:
URL:
  情報を記憶: 評価:  顔   星
 
 
 
Search
Categories
Recents
Links
Archives
livedoor Readerに登録
RSS
livedoor Blog(ブログ)