DIV CSS 佈局教程網

輸入框取得焦點時自動清除提示文字的實作
編輯:JavaScript綜合知識     

為節省表單空間,常以提示文字佔位,並在使用者點入時自動清除。本文示範兩種做法:直接寫在標籤事件上,以及透過外部函式控制。

程式碼如下:

<!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)直接將邏輯寫在 onfocus 與 onblur 上:取得焦點時若內容仍是提示文字就清空並換上 active 樣式,失去焦點時若為空則還原提示。第二個輸入框(bbb)則透過外部的 clearFiled 函式處理點擊清空,並以 document.onmousedown 判斷是否需還原提示。兩種方式都能兼顧提示文字的顯示與清除,可依團隊習慣挑選。

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