当前位置: 移动技术网 > IT编程>开发语言>JavaScript > JavaScript实现的文本框placeholder提示文字功能示例

JavaScript实现的文本框placeholder提示文字功能示例

2018年08月10日  | 移动技术网IT编程  | 我要评论

本文实例讲述了javascript实现的文本框placeholder提示文字功能。分享给大家供大家参考,具体如下:

<!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>

感兴趣的朋友可以使用在线html/css/javascript代码运行工具:测试一下运行效果。

更多关于javascript相关内容感兴趣的读者可查看本站专题:《javascript页面元素操作技巧总结》、《javascript操作dom技巧总结》、《javascript切换特效与技巧总结》、《javascript动画特效与技巧汇总》、《javascript错误与调试技巧总结》、《javascript数据结构与算法技巧总结》及《javascript数学运算用法总结

希望本文所述对大家javascript程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网