效果圖如下:
<!-- 當文本框獲得焦點時候,如果文本框內容是 請輸入搜索關鍵字 清空文本框,輸入內容變黑色 --> <!-- 當文本框失去焦點時候,如果文本框無內容,則添加灰色的 請輸入搜索關鍵字 內容,否則,不改變 -->
注意事件:
1、點擊焦點事件----onfouce
2、失去焦點事件----onblur
3、對於元素屬性的訪問,class,應該是元素名.className
代碼如下:
1 <!DOCTYPE html> 2 <html> 3 <head lang="en"> 4 <meta charset="UTF-8"> 5 6 <title>文本框的焦點事件</title> 7 8 <style type="text/css"> 9 /* 灰色 */ 10 .gray{ 11 color: gray; 12 } 13 14 /* 黑色 */ 15 .black{ 16 color: black; 17 } 18 </style> 19 20 </head> 21 <body> 22 <!-- 當文本框獲得焦點時候,如果文本框內容是 請輸入搜索關鍵字 清空文本框,輸入內容變黑色 --> 23 <!-- 當文本框失去焦點時候,如果文本框無內容,則添加灰色的 請輸入搜索關鍵字 內容,否則,不改變 --> 24 <input type="text" id="txtSearch" class="gray" value="請輸入搜索關鍵字" /> 25 26 <!-- 添加JS效果 --> 27 <script type="text/javascript"> 28 //獲得文本框元素 29 var txtSearch=document.getElementById('txtSearch'); 30 31 //文本框得到焦點事件 onfocus() 32 txtSearch.onfocus=function(){ 33 if(this.value==='請輸入搜索關鍵字'){//判斷 34 this.className='black'; 35 this.value=''; 36 } 37 } 38 39 //文本框失去焦點事件 onblur() 40 txtSearch.onblur=function(){ 41 if(this.value.length==0){ 42 this.value='請輸入搜索關鍵字'; 43 this.className='gray'; 44 } 45 } 46 </script> 47 </body> 48 </html>