版本一
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>
做個邏輯判斷,如果值為默認值,就將文本框中的內容清空。
失去焦點,如果文本框中為空,也就是沒有輸入內容,就將值還設為默認值。
這是一個簡單的邏輯。