广告位联系
返回顶部
分享到

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

JavaScript 来源:互联网搜集 作者:酷站 发布时间:2018-07-28 08:22:12 人浏览
摘要

今天小编给大家带来JavaScript实现的文本框placeholder提示文字功能示例教程 !doctype htmlhtmlheadmeta http-equiv=Content-Type content=text/html; charset=utf-8 /titlewww.jb51.net JS文本框placeholder提示/title/headbody input id=input type=text v

今天小编给大家带来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代码运行工具:http://tools.jb51.net/code/HtmlJsRun测试一下运行效果。


版权声明 : 本文内容来源于互联网或用户自行发布贡献,该文观点仅代表原作者本人。本站仅提供信息存储空间服务和不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权, 违法违规的内容, 请发送邮件至2530232025#qq.cn(#换@)举报,一经查实,本站将立刻删除。
原文链接 :
相关文章
  • 本站所有内容来源于互联网或用户自行发布,本站仅提供信息存储空间服务,不拥有版权,不承担法律责任。如有侵犯您的权益,请您联系站长处理!
  • Copyright © 2017-2022 F11.CN All Rights Reserved. F11站长开发者网 版权所有 | 苏ICP备2022031554号-1 | 51LA统计