經過查詢,發現2種實現方式:
1.
<input type="text" value="請輸入用戶名" onfocus="if(value=='請輸入用戶名') {value=''}" onblur="if (value=='') {value='請輸入用戶名'}">
直接在input中定義onfocus和onblur事件,缺點:鼠標一離開就顯示提示文字,輸入框中用戶的輸入也會消失。
2.提示文字根據焦點自動消失的輸入框javascript
2的功能較1來說較全面,代碼也稍復雜一點,功能包括:
鼠標點擊輸入框,輸入框獲得焦點時,提示文字自動消失
鼠標焦點離開輸入框,提示文字根據情況顯示
輸入框html代碼
<input id="searchKey" type="text" name="q" value="" tips="請輸入關鍵字"/><br />
<script language="javascript" type="text/javascript"> window.onload = function(){ var o=document.getElementByIdx_x("searchKey"); o.setAttribute("valueCache",o.value); o.onblur = function(){ if(o.value=="") { o.valueCache=""; o.value=o.tips; } else o.valueCache=o.value; } o.onfocus = function(){ o.value=o.valueCache; //光標始終在文字最后 var e = event.srcElement; var r =e.createTextRange(); r.moveStart('character',e.value.length); r.collapse(true); r.select(); } o.onblur(); } <script>