使用できることはわかってplaceholder="some text here..."
いますが、フォーカスの代わりにキーを押すとテキストが削除されるようにするにはどうすればよいですか? CSSを使用することは可能ですか、またはjQueryを使用してそれを達成する方法はありますか?
3609 次
5 に答える
1
完璧ではありませんが、新しいブラウザーのようなプレースホルダーを作成する方法を次に示します。
JS--
//when the input is clicked, select it's text so the cursor doesn't start typing in the middle of your placeholder text
$('input').on('click', function () {
//by selecting the input on click we mimic the focus event
$(this).select();
}).on('keyup', function () {
//if the input is un-touched
if (this.value == '' || this.value == '[Your Name]') {
//make the input in-active
this.className = '';
//and make sure the placeholder is still showing
this.value = '[Your Name]';
} else {
//since something has been entered into the input, add the active class to make the text black
this.className = 'active';
}
});
CSS --
input {
color : grey;
}
input.active {
color : black;
}
これにより、入力はデフォルトで灰色のテキストになり、ユーザーが何かを入力すると黒くなります。
HTML --
<input type="text" value="[Your Name]" />
ここにデモがあります:http://jsfiddle.net/2VfwW/
プレースホルダーを属性に追加し、placeholder
その属性のサポートを確認し、存在しない場合は上記のコードを実行できますが、各入力の値をplaceholder
属性の値にすることから始めます。
$(function () {
//find all input elements with a placeholder attribute
$('input[placeholder]').val(function () {
//set the value of this input to the value of its placeholder
return $(this).attr('placeholder');
});
});
于 2012-04-05T19:14:20.800 に答える
0
テキスト フィールドに値があり、ユーザーがテキスト フィールドにキーを入力したときにのみ値をクリアしたい場合は、次のようにします。
$("#myTextfield").keypress(function() {
$(this).val("");
});
この次のビットは、ユーザーがテキスト フィールドに何かを入力したかどうかを確認します。そうでない場合は、フォーカスを失ったときにプレースホルダーを追加します。
$("#myTextfield").blur(function() {
if($(this).val() === "") {
$(this).val("Search...");
}
});
于 2012-04-05T19:12:26.387 に答える
0
以下のような jQuery のようなものが動作するはずです。
$('#myElement').keypress(function() { this.val = ''; }
于 2012-04-05T19:11:26.567 に答える
0
Javascript の使用:
<input type="text" onfocus="if(this.value == 'Your text'){this.value=''}" value='Your text' />
于 2012-04-05T19:11:44.597 に答える