本文實例講述了JavaScript實現(xiàn)的文本框placeholder提示文字功能。分享給大家供大家參考,具體如下:
<!doctype html><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>www.survivalescaperooms.com JS文本框placeholder提示</title></head><body> <input id="input" type="text" value="請輸入關(guān)鍵詞"></body><script> window.onload = function() { var defaultValue = "請輸入關(guān)鍵詞"; var input = document.getElementById("input"); input.style.color = "grey"; input.onfocus = function() { if (this.value == defaultValue) { input.value=""; setCursorPosition(this, 0); } }; input.onblur = function() { if (this.value == "") { this.value = defaultValue; } }; input.onkeypress = function(e) { e = e || window.event; var key = e.charCode || e.keyCode || e.which; if (this.value == defaultValue) { this.value = ""; this.style.color = "black"; } if (this.value.length == 1 && key == 8) { this.value = defaultValue; this.style.color = "grey"; setCursorPosition(this, 0); } }; }; function setCursorPosition(elem, index) { if (elem.setSelectionRange) { elem.focus(); elem.setSelectionRange(index, index); } else if (elem.createTextRange) { var range = elem.createTextRange(); range.collapse(true); range.moveEnd('character', index); range.moveStart('character', index); range.select(); } }</script></html>感興趣的朋友可以使用在線HTML/CSS/JavaScript代碼運行工具:http://tools.Vevb.com/code/HtmlJsRun測試一下運行效果。
更多關(guān)于JavaScript相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《JavaScript頁面元素操作技巧總結(jié)》、《JavaScript操作DOM技巧總結(jié)》、《JavaScript切換特效與技巧總結(jié)》、《JavaScript動畫特效與技巧匯總》、《JavaScript錯誤與調(diào)試技巧總結(jié)》、《JavaScript數(shù)據(jù)結(jié)構(gòu)與算法技巧總結(jié)》及《JavaScript數(shù)學(xué)運算用法總結(jié)》
希望本文所述對大家JavaScript程序設(shè)計有所幫助。
新聞熱點
疑難解答
圖片精選