JavaScript實(shí)現(xiàn)的文本框placeholder提示文字功能示例
本文實(shí)例講述了JavaScript實(shí)現(xiàn)的文本框placeholder提示文字功能。分享給大家供大家參考,具體如下:
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>www.fzitv.net JS文本框placeholder提示</title>
</head>
<body>
<input id="input" type="text" value="請(qǐng)輸入關(guān)鍵詞">
</body>
<script>
window.onload = function() {
var defaultValue = "請(qǐng)輸入關(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代碼運(yùn)行工具:http://tools.jb51.net/code/HtmlJsRun測(cè)試一下運(yùn)行效果。
更多關(guān)于JavaScript相關(guān)內(nèi)容感興趣的讀者可查看本站專(zhuān)題:《JavaScript頁(yè)面元素操作技巧總結(jié)》、《JavaScript操作DOM技巧總結(jié)》、《JavaScript切換特效與技巧總結(jié)》、《JavaScript動(dòng)畫(huà)特效與技巧匯總》、《JavaScript錯(cuò)誤與調(diào)試技巧總結(jié)》、《JavaScript數(shù)據(jù)結(jié)構(gòu)與算法技巧總結(jié)》及《JavaScript數(shù)學(xué)運(yùn)算用法總結(jié)》
希望本文所述對(duì)大家JavaScript程序設(shè)計(jì)有所幫助。
相關(guān)文章
經(jīng)典的間隔時(shí)間滾動(dòng)新聞(圖片),可控制滾動(dòng)
經(jīng)典的間隔時(shí)間滾動(dòng)新聞(圖片),可控制滾動(dòng) 其實(shí)這個(gè)也挺多網(wǎng)站用到的,簡(jiǎn)單又實(shí)用。(2010-05-05
基于Bootstrap table組件實(shí)現(xiàn)多層表頭的實(shí)例代碼
Bootstrap table還有一個(gè)很多強(qiáng)大的功能,下面就通過(guò)本文給大家分享基于Bootstrap table組件實(shí)現(xiàn)多層表頭的實(shí)例代碼,需要的朋友參考下吧2017-09-09
js get和post請(qǐng)求實(shí)現(xiàn)代碼解析
這篇文章主要介紹了js get和post實(shí)現(xiàn)代碼解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-02-02
JS動(dòng)態(tài)更改div高度實(shí)現(xiàn)代碼例子
在Web開(kāi)發(fā)中通過(guò)使用JavaScript可以動(dòng)態(tài)地修改HTML元素的屬性和樣式,下面這篇文章主要給大家介紹了關(guān)于JS動(dòng)態(tài)更改div高度實(shí)現(xiàn)的相關(guān)資料,文中給出了詳細(xì)的代碼示例,需要的朋友可以參考下2023-11-11

