jQuery 文字框得失焦點的執行個體介紹
本篇文章主要是對jQuery 文字框得失焦點的簡單一實例進行了介紹,需要的朋友可以過來參考下,希望對大家有所協助
版本一
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>
這裡有兩個input,一個textare框。
: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,通過$(this)自動識別當前的元素。focus()方法是擷取焦時間點事件發生時執行的函數。blur()方法是失去焦時間點事件發生時執行的函數。
版本二:
有時候文字框裡有預設的內容,作為提示資訊,擷取焦點後,要讓它消失。可以做如下的改造:
代碼如下:
<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>
做個邏輯判斷,如果值為預設值,就將文字框中的內容清空。
失去焦點,如果文字框中為空白,也就是沒有輸入內容,就將值還設為預設值。
這是一個簡單的邏輯。