JavaScript實現的文本框placeholder提示文字功能示例
更新時間:2018年07月25日 11:57:56 作者:筱葭
這篇文章主要介紹了JavaScript實現的文本框placeholder提示文字功能,涉及javascript事件響應及頁面元素屬性動態(tài)操作相關實現技巧,需要的朋友可以參考下
本文實例講述了JavaScript實現的文本框placeholder提示文字功能。分享給大家供大家參考,具體如下:
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>www.dbjr.com.cn 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>
感興趣的朋友可以使用在線HTML/CSS/JavaScript代碼運行工具:http://tools.jb51.net/code/HtmlJsRun測試一下運行效果。
更多關于JavaScript相關內容感興趣的讀者可查看本站專題:《JavaScript頁面元素操作技巧總結》、《JavaScript操作DOM技巧總結》、《JavaScript切換特效與技巧總結》、《JavaScript動畫特效與技巧匯總》、《JavaScript錯誤與調試技巧總結》、《JavaScript數據結構與算法技巧總結》及《JavaScript數學運算用法總結》
希望本文所述對大家JavaScript程序設計有所幫助。
相關文章
經過綁定元素時會多次觸發(fā)mouseover和mouseout事件
經過綁定元素時會多次觸發(fā)mouseover和mouseout事件,針對這個問題,下面有個不錯的解決方法2014-02-02

