HTML5
HTML5 は、この機能のネイティブ サポートを有効にするという<input>
タグの便利な属性をもたらします。placeholder
jsフィドル
<input type="text" placeholder="Search..." />
サポート
最新のブラウザはすべてこれをサポートしていますが、IE9 以下はサポートしていません。
<label>
placeholder 属性は、すべての入力に必要な<label>
タグの代わりになるものではないことに注意してください<input>
。ユーザーに表示されない場合でも、ラベルを含めるようにしてください。
<label for="search">Search</label>
<input id="search" placeholder="Search..." />
上記<label>
は非表示にできるため、次のような支援技術で引き続き使用できます。
label[for=search] {
position:absolute;
left:-9999px;
top:-9999px;
}
クロスブラウザ ソリューション
クロスブラウザー ソリューションとして考えられるのは次のとおりです。コードをタグからスクリプト タグに移動し、クラスを使用しplaceholder
てテキストをフェードするタイミングを示しました。
jsフィドル
HTML
<input name="firstName" type="text" maxlength="40" value="Enter your first name"
class="placeholder" id="my-input" />
CSS
input[type=text].placeholder {
color: #999;
}
JS
<script type="text/javascript">
var input = document.getElementById('my-input');
input.onfocus = function () {
if (this.value == this.defaultValue && this.className == 'placeholder') {
this.value = '';
}
this.className = '';
};
input.onblur = function() {
if (this.value == '') {
this.className = 'placeholder';
this.value = this.defaultValue;
}
};
</script>
すべてに適用input[type=text]
input[type=text]
上記のソリューションを拡張して、を使用しdocument.getElementsByTagName()
、それらをループして、 でtype
属性をチェックすることで、すべてに適用できますelement.getAttribute()
。
jsフィドル
var input = document.getElementsByTagName('input');
for (var i = 0; i < input.length; i++) {
if (input[i].getAttribute('type') === 'text') {
input[i].onfocus = inputOnfocus;
input[i].onblur = inputOnblur;
}
}
function inputOnfocus () {
if (this.value == this.defaultValue && this.className == 'placeholder') {
this.value = '';
}
this.className = '';
}
function inputOnblur() {
if (this.value == '') {
this.className = 'placeholder';
this.value = this.defaultValue;
}
}