JavaScript实现的文本框placeholder提示文字功能示例
会计网 2018-09-14 1260
本文实例讲述了JavaScript实现的文本框placeholder提示文字功能。分享给大家供大家参考,具体如下:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | <!doctype html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>www.jb51.net 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> |