JavaScript实现文本框的placeholder

代码: <!doctype html>  <html>      <head>        </head>      <body>  <input id="input" type="text" value="请输入关键词">     </body>  &...

代码:

<!doctype html>  
<html>  
    <head>    
    </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) {
setCursorPosition(this, 0);
}
};
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> 

你可能感兴趣的文章

相关问题

0 条评论

请先 登录 后评论
廖雪
廖雪

78 篇文章

作家榜 »

  1. admin 651 文章
  2. 粪斗 185 文章
  3. 王凯 92 文章
  4. 廖雪 78 文章
  5. 牟雪峰 12 文章
  6. 李沁雪 9 文章
  7. 全易 2 文章
  8. Stevengring 0 文章