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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

筱葭   2020-05-16 我要评论

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

<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>www.qb5200.com 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.softyun.net/code/HtmlJsRun测试一下运行效果。

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

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们