質問:
特定のテキスト ボックスがフォーカスを受け取ると、キャレットをテキスト ボックスの末尾に設定します。このソリューションは、IE7、Opera、Chrome、および Firefox で動作する必要があります。
少し簡単にするために、この動作は、テキスト ボックスの現在の値が固定値である場合にのみ必要です。(「INIT」と言います)
不完全なソリューション:
これは非常に単純であると予想されますが、すべてのブラウザーで機能する SO に関する回答を見つけることができませんでした。次の答えは機能しません。
$("#test").focus(function() {
// This works for Opera only
// Also tested with $(this).val($(this).val());
if (this.value == "INIT") {
this.value = "";
this.value = "INIT";
}
});
$("#test").focus(function() {
// This works for IE and for Opera
if (this.value == "INIT") {
setCaretPosition(this, 4);
}
});
SO の質問から setCaretPosition 関数を取得し、さまざまなブログでも見ました。
function setCaretPosition(ctrl, pos) {
if (ctrl.setSelectionRange) {
//ctrl.focus(); // can't focus since we call this from focus()
// IE only
ctrl.setSelectionRange(pos, pos);
}
else if (ctrl.createTextRange) {
// Chrome, FF and Opera
var range = ctrl.createTextRange();
range.collapse(true);
range.moveEnd('character', pos); // Also tested with this
range.moveStart('character', pos); // and this line in comment
range.select();
}
}
フィドル
jsFiddleをセットアップしました。