jQuery を使用してテキスト フィールドのカーソル位置を設定するにはどうすればよいでしょうか。コンテンツを含むテキスト フィールドがあり、ユーザーがフィールドにフォーカスしたときにカーソルを特定のオフセットに配置する必要があります。コードは次のようになります。
$('#input').focus(function() {
$(this).setCursorPosition(4);
});
setCursorPosition 関数の実装はどのようになるでしょうか? コンテンツ abcdefg を持つテキスト フィールドがある場合、この呼び出しによりカーソルは次のように配置されます: abcd**|**efg。
Java には同様の関数 setCaretPosition があります。JavaScript にも同様のメソッドがありますか?
更新: CMS のコードを次のように変更して、jQuery で動作するようにしました。
new function($) {
$.fn.setCursorPosition = function(pos) {
if (this.setSelectionRange) {
this.setSelectionRange(pos, pos);
} else if (this.createTextRange) {
var range = this.createTextRange();
range.collapse(true);
if(pos < 0) {
pos = $(this).val().length + pos;
}
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
}
}(jQuery);
ベストアンサー1
jQuery ソリューションは次のとおりです。
$.fn.selectRange = function(start, end) {
if(end === undefined) {
end = start;
}
return this.each(function() {
if('selectionStart' in this) {
this.selectionStart = start;
this.selectionEnd = end;
} else if(this.setSelectionRange) {
this.setSelectionRange(start, end);
} else if(this.createTextRange) {
var range = this.createTextRange();
range.collapse(true);
range.moveEnd('character', end);
range.moveStart('character', start);
range.select();
}
});
};
これにより、
$('#elem').selectRange(3,5); // select a range of text
$('#elem').selectRange(3); // set cursor position