dom里面失去焦点onblur和获取焦点onfocus的使用

138 阅读1分钟

image.png

<!DOCTYPE html>
<html>
  <head lang="en">
    <meta charset="UTF-8" />
    <title>onblur和onfocus</title>
    <style type="text/css">
      .red {
        border: 1px solid red;
      }
    </style>
  </head>
  <body>
    姓名:<input type="text" /> <span></span>
    <script>
      var input = document.querySelector("input");
      var span = document.querySelector("span");
      //   获得焦点
      input.onfocus = function () {
        if (input.value.length === 0) {
          span.innerHTML = "请输入用户名";
        }
      };
      //   失去焦点
      input.onblur = function () {
        if (input.value.length === 0) {
          span.innerHTML = "用户名不能为空";
          this.className = "red";
        } else {
          this.className = "";
          span.innerHTML = "";
        }
      };
    </script>
  </body>
</html>