js textarea、テキストフィールドのキャレットの位置(カーソル位置)を変更したい(setSelectionRange())
好きな場所にカーソルを移動させたい
作成日:2019-12-27, 更新日:2019-12-27
基本
・「setSelectionRange()」を使う感じ。
・jqueryの「$(〇〇〇)」を使う感じで「$(〇〇〇).setSelectionRange()」はダメ。ひと手間加えればOK・・・だけど、ひと手間加える必要が無いので放置。
サンプル
・Chrome以外では確認していない
・面倒なので対象のtextarea(or テキストフィールド)にIDを割振る
・テキストフィールドの場合、カーソル位置を変更しても対象のトコまでスクロールされないので「blur()」「focus()」を追記する
var move_caret = function(elm_id, pos_fst, pos_end) {
if ( pos_end == null) {
pos_end = pos_fst;
}
var elm = document.getElementById(elm_id);
if (elm.setSelectionRange) {
elm.setSelectionRange(pos_fst, pos_end);
}
else if (elm.createTextRange) {
// 「setSelectionRange()」が対応されていないブラウザ用
var range = elm.createTextRange();
range.move('character', pos_fst);
range.select();
}
else {
//alert('このブラウザではカーソルの移動は無理');
console.log('このブラウザではカーソルの移動は無理');
}
elm.blur();
elm.focus();
return null;
}
move_caret(ID, 始点の文字数, 終点の文字数);