テキストエリアのカーソルを操作する - Javascript

テキストエリアの操作

HTML

<p id="btn" accesskey="U">click</p>
<textarea id="target"></textarea>

CSS

#target {
  border: 1px solid gray;
  padding: 10px;
}
#btn {
  border: 1px solid gray;
  padding: 2px 4px;
  width: 50px;
  text-align: center;
}

accesskeyをinputタグやbuttonタグに設定すると、textareaからフォーカスが移るため使用する場合は、別のタグで代用します。

カーソルの位置に文字を挿入する

selectionStartは、「 HTMLTextAreaElement 」と「 HTMLInputElement 」のプロパティでinput要素とtextarea要素のテキスト入力カーソルの位置を返します。

「 HTMLInputElement 」要素の注意点は、text、search、URL、tel、password の各入力型にのみ適用されます。それ以外の入力型に selectionStart プロパティを設定すると例外が発生します。

文字の分割をsubstr()で記載しているサイトがありますが、現在では非推奨のため、substringもしくはsliceを使用します。

const btn = document.getElementById('btn');
const target_area = document.getElementById('target');

btn.addEventListener('click', function(){
  const start = target_area.selectionStart;
  const end = target_area.selectionEnd;
  const txt = target_area.value;

  target_area.value = txt.substring(0, start) + "<br>" + txt.substring(end);
})

「 element.selectionStart 」で、開始位置を取得できます。カーソルがtextareaの先頭の場合、「 0 」を返します。

また、カーソルの開始位置を設定する際にも使用します。

element.selectionStart = 1;

「 element.selectionEnd 」で、終了位置を取得できます。範囲選択していない場合、「 selectionStart 」と同じ値になります。

また、カーソルの終了位置を設定する際にも使用します。

element.selectionEnd = 1;

範囲選択する場合は、「 selectionStart 」と「 selectionEnd 」をそれぞれ設定します。

「 selectionStart 」が「 selectionEnd 」よりも大きくなった場合、「 selectionEnd 」の位置を取得します。

以下の場合は、2文字目を選択した状態にします。以下の例もアクセスキーでアクセスすると範囲選択された状態を確認することができます。

const btn = document.getElementById('btn');

btn.addEventListener('click', function(){
  target_area.selectionStart = 1;
  target_area.selectionEnd = 2;
})

選択した前後に文字を挿入する

選択した前後に文字を挿入するには、textarea にセットする値を次のように変更します。

 target_area.value = txt.substring(0, start)
  + "<h1>"
  + txt.substring(start, end)
  + "</h1>"
  + txt.substring(end);

開始タグの直後にカーソルを移動するには、以下のようにします。

p#btn要素をクリックするのではなく、アクセスキーを使用すると開始タグ(<h1>)の後にカーソルが移動します。

取得したカーソルの位置に<h1>の4文字分を足してカーソルの位置を移動させます。

const btn = document.getElementById('btn');
const target_area = document.getElementById('target');

btn.addEventListener('click', function(){
  const start = target_area.selectionStart;
  const end = target_area.selectionEnd;
  const txt = target_area.value;

  target_area.value = txt.substring(0, start)
    + "<h1>"
    + txt.substring(start, end)
    + "</h1>"
    + txt.substring(end);
  
  target_area.selectionStart = start + "<h1>".length;
  target_area.selectionEnd = start + "<h1>".length;
})

click