Jquery使用Id獲取焦點和失去焦點有2種方法
先用第一種(val()=="空"):
<div> <input type="text" id="address" value="請輸入郵箱地址" /> <input type="text" id="password" value="請輸入郵箱密碼" /> <input type="button" value="登錄" /> </div> <script type="text/javascript"> $("#address").focus(function () { //focus獲取鼠標焦點時,如果輸入框的值為 "請輸入郵箱地址" ,則將輸入框中的值清空 var txt_value = $(this).val(); //獲取地址文本框的值 if (txt_value == "請輸入郵箱地址") { $(this).val(""); } }); $("#address").blur(function () { //blur失去鼠標焦點時,如果輸入框的值為空,則將輸入框中的值為 "請輸入郵箱地址" var txt_value = $(this).val(); //獲取地址文本框的值 if (txt_value == "") { $(this).val("請輸入郵箱地址"); } }); $("#password").focus(function () { //focus獲取鼠標焦點時,如果輸入框的值為 "請輸入郵箱密碼" ,則將輸入框中的值清空 var txt_value = $(this).val(); //獲取地址文本框的值 if (txt_value == "請輸入郵箱密碼") { $(this).val(""); } }); $("#password").blur(function () { //blur失去鼠標焦點時,如果輸入框的值為空,則將輸入框中的值為 "請輸入郵箱密碼" var txt_value = $(this).val(); //獲取地址文本框的值 if (txt_value == "") { $(this).val("請輸入郵箱密碼"); } }); </script>
這是第二種(defaultValue):
<div> <input type="text" id="address" value="請輸入郵箱地址" /> <input type="text" id="password" value="請輸入郵箱密碼" /> <input type="button" value="登錄" /> </div> <script type="text/javascript"> //還可以使用表單元素的defaultValue屬性來實現同樣的功能 $("#address").focus(function () { var txt_value = $(this).val(); if (txt_value == this.defaultValue) { //this指向當前的文本框,this.defaultValue 就是當前文本框的默認值 $(this).val(""); } }); $("#address").blur(function () { var txt_value = $(this).val(); if (txt_value =="") { $(this).val(this.defaultValue); } }); $("#password").focus(function () { var txt_value = $(this).val(); if (txt_value == this.defaultValue) { $(this).val(""); } }); $("#password").blur(function () { var txt_value = $(this).val(); if (txt_value == "") { $(this).val(this.defaultValue); } }); </script>