本文實例講述了JavaScript實現的文本框placeholder提示文字功能。分享給大家供大家參考,具體如下:
<!doctype html><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>www.49028c.com JS文本框placeholder提示</title></head><body> <input id="input" type="text" value="請輸入關鍵詞"></body><script> window.onload = function() { var defaultValue = "請輸入關鍵詞"; 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>
希望本文所述對大家JavaScript程序設計有所幫助。
新聞熱點
疑難解答