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

作者:微光时间:2026-10-22 16:12:22浏览:496

本文介绍如何使用JavaScript模拟文本框的placeholder提示文字效果。通过获取输入框元素,设置初始灰色字体颜色,并在聚焦时清空内容、失去焦点时恢复默认值,实现类似HTML5 placeholder的交互体验,适用于兼容旧版浏览器的场景。

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

本文详细介绍如何利用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 测试运行效果。

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

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

作者最新文章