DIV CSS 佈局教程網

JS 輸入框獲焦時自動清除提示文字的實現方法
編輯:關於JavaScript     

很多表單會在輸入框裡預置一段灰色提示文字,當用戶點擊輸入時自動清空,離開時若為空則還原提示。這種交互能兼顧引導性與簡潔度。下面示例提供了兩種寫法:一種直接寫在標簽的 onfocus/onblur 上,另一種透過 JS 函數配合全局 mousedown 事件處理。

代碼如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>無標題文檔</title>
<style type="text/css">
.clearFieldBlurred{
    color:#ccc;
    font-style:italic;
    font-weight:normal;
    width:150px;
}
.clearFieldActive{
    color:#4e4e4e;
    font-weight:bold;
    width:150px;
}
</style>
<script type="text/javascript">
function clearFiled(){
    var bbb=document.getElementById("bbb");
    if(bbb.value=="bbb"){
        bbb.value='';
        bbb.className='clearFieldActive';
    }
}
window.document.onmousedown=function(){
    var bbb=document.getElementById('bbb');
    if(bbb.value==""){
        bbb.value='bbb';
        bbb.className='clearFieldBlurred';
    }
}
</script>
</head>
<body>
<input type="text" id="aaa"  value="aaa" class="clearFieldBlurred" onfocus="if(this.value=='aaa'){this.value='';this.className='clearFieldActive';}"  onblur="if(this.value==''){this.value='aaa';this.className='clearFieldBlurred';}"/>
<br />
<input type="text" id="bbb" value="bbb" class="clearFieldBlurred" onclick="clearFiled()"  />
</body>
</html>

第一個輸入框 aaa 直接把判斷邏輯寫在行內事件中;第二個 bbb 則藉由 clearFiled 函數在獲焦時清空,並透過 window.onmousedown 在別處點擊時判斷是否還原提示。兩種做法原理一致,可依維護需求挑選。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved