jQueryテキストボックスの损得焦点の简単な例
バージョン1
cssコード部分:
htmlコード部分:
:inputはすべてのinput、textarea、selectとbutton元素にマッチします。
jQueryコード部分:
バージョン2:
テキストボックスにはデフォルトの内容があります。ヒントとしてフォーカスを取得したら消えます。
フォーカスが失われ、テキストボックスが空である場合、つまり入力されていない場合は、値をデフォルトに設定します。
これは簡単なロジックです。
cssコード部分:
.focus {
border: 1px solid #f00;
background: #fcc;
}
フォーカスを取得すると、focusスタイルを追加し、枠を追加して、背景色を芰fccに変更します。htmlコード部分:
<body>
<form action="" method="post" id="regForm">
<fieldset>
<legend> </legend>
<div>
<label for="username"> :</label>
<input id="username" type="text" />
</div>
<div>
<label for="pass"> :</label>
<input id="pass" type="password" />
</div>
<div>
<label for="msg"> :</label>
<textarea id="msg" rows="2" cols="20"></textarea>
</div>
</fieldset>
</form>
</body>
ここには2つのinputがあります。一つのtextartボックスです。:inputはすべてのinput、textarea、selectとbutton元素にマッチします。
jQueryコード部分:
<script type="text/javascript">
$(function(){
$(":input").focus(function(){
$(this).addClass("focus");
}).blur(function(){
$(this).removeClass("focus");
});
})
</script>
用:inputはすべてのinput要素にマッチしています。焦点を取得すると、スタイルfocusを追加して、現在の要素を自動的に認識します。フォーカスイベントの発生時に実行する関数を取得する方法です。blur()メソッドは、フォーカスイベントが発生したときに実行される関数です。バージョン2:
テキストボックスにはデフォルトの内容があります。ヒントとしてフォーカスを取得したら消えます。
<script type="text/javascript">
$(function(){
$(":input").focus(function(){
$(this).addClass("focus");
if($(this).val() ==this.defaultValue){
$(this).val("");
}
}).blur(function(){
$(this).removeClass("focus");
if ($(this).val() == '') {
$(this).val(this.defaultValue);
}
});
})
</script>
で論理判断ができます。標準値であればテキストボックスの内容をクリアします。フォーカスが失われ、テキストボックスが空である場合、つまり入力されていない場合は、値をデフォルトに設定します。
これは簡単なロジックです。