[解決済み] 負荷時のフォーカス入力ボックス
2022-11-14 02:08:35
質問
ページロード時に特定の入力ボックスにカーソルを合わせるにはどうしたらよいでしょうか?
テキストの初期値も保持し、入力の最後にカーソルを置くことは可能ですか?
<input type="text" size="25" id="myinputbox" class="input-text" name="input2" value = "initial text" />
どのように解決するのですか?
あなたの質問には2つの部分があります。
1) ページロード時に入力にフォーカスする方法は?
あなたはただ
autofocus
属性を入力に追加します。
<input id="myinputbox" type="text" autofocus>
しかし、これはすべてのブラウザでサポートされていないかもしれないので、javascriptを使用します。
window.onload = function() {
var input = document.getElementById("myinputbox").focus();
}
2) カーソルを入力テキストの末尾に配置するには?
以下は、jQuery以外の解決策で、以下のコードから借用したものです。 別のSO回答 .
function placeCursorAtEnd() {
if (this.setSelectionRange) {
// Double the length because Opera is inconsistent about
// whether a carriage return is one character or two.
var len = this.value.length * 2;
this.setSelectionRange(len, len);
} else {
// This might work for browsers without setSelectionRange support.
this.value = this.value;
}
if (this.nodeName === "TEXTAREA") {
// This will scroll a textarea to the bottom if needed
this.scrollTop = 999999;
}
};
window.onload = function() {
var input = document.getElementById("myinputbox");
if (obj.addEventListener) {
obj.addEventListener("focus", placeCursorAtEnd, false);
} else if (obj.attachEvent) {
obj.attachEvent('onfocus', placeCursorAtEnd);
}
input.focus();
}
jQueryでこれを実現する例を挙げます。
<input type="text" autofocus>
<script>
$(function() {
$("[autofocus]").on("focus", function() {
if (this.setSelectionRange) {
var len = this.value.length * 2;
this.setSelectionRange(len, len);
} else {
this.value = this.value;
}
this.scrollTop = 999999;
}).focus();
});
</script>
関連
-
[解決済み] Webフォームのフィールド/入力タグでブラウザのオートコンプリートを無効にするにはどうすればよいですか?
-
[解決済み] jQueryを使ってドロップダウンリスト(セレクトボックス)から選択されたテキストを取得する
-
[解決済み] セレクトボックスのプレースホルダーを作成するにはどうすればよいですか?
-
[解決済み] どのDOM要素にフォーカスがあるかを調べるには?
-
[解決済み] テキストボックスのEnterキーで、JavaScriptでボタンクリックをトリガーする
-
[解決済み] JavaScriptでテキスト入力フィールドの値を取得するにはどうすればよいですか?
-
[解決済み] 入力にフォーカスがあるかどうかをテストするためにjQueryを使用する
-
[解決済み] JavaScript を使ってテキスト入力要素のテキストの末尾にカーソルを配置する
-
[解決済み] jQueryを使用して、ページロード時にフォーム入力のテキストフィールドに焦点を当てるには?
-
[解決済み] なぜJavaScriptでは!{}[true]がtrueに評価されるのですか?
最新
-
nginxです。[emerg] 0.0.0.0:80 への bind() に失敗しました (98: アドレスは既に使用中です)
-
htmlページでギリシャ文字を使うには
-
ピュアhtml+cssでの要素読み込み効果
-
純粋なhtml + cssで五輪を実現するサンプルコード
-
ナビゲーションバー・ドロップダウンメニューのHTML+CSSサンプルコード
-
タイピング効果を実現するピュアhtml+css
-
htmlの選択ボックスのプレースホルダー作成に関する質問
-
html css3 伸縮しない 画像表示効果
-
トップナビゲーションバーメニュー作成用HTML+CSS
-
html+css 実装 サイバーパンク風ボタン
おすすめ
-
[解決済み] JavaScript を使ってテキスト入力要素のテキストの末尾にカーソルを配置する
-
[解決済み] JavaScriptのtoString()関数をオーバーライドして、デバッグ用に意味のある出力を提供することは可能でしょうか?
-
[解決済み] react-routerのハッシュフラグメントからクエリパラメータを取得する
-
[解決済み] BlobからArrayBufferへ移行する方法
-
[解決済み] Reactメモを使うべきではない場合とは?
-
[解決済み] jQueryで入力ファイルが空かどうかをチェックする方法
-
[解決済み] Node.jsのES6クラスをrequireで作る
-
[解決済み] V8 Javascript エンジンのスタンドアロン実行
-
[解決済み] これは純関数ですか?
-
[解決済み] リダイレクトされずにHTMLフォームを送信する方法