密码框验证信息+显示与隐藏 练习

DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>密码框验证信息+显示与隐藏title>
  <style>
    .register {
      width: 400px;
      margin: 100px auto;
    }

    .pass {
      position: relative;
      display: inline-block;
      width: 200px;
      border: 1px solid #ccc;
    }

    .pass input {
      width: 170px;
      border: 0px;
      outline: none;
    }

    .pass img {
      position: absolute;
      /* 子绝父相 */
      top: 2px;
      right: 2px;
      width: 15px;
      margin: 3px 2px 0px;
    }

    .hint {
      display: inline-block;
    }

    .hint span {
      color: red;
      vertical-align: middle;
      /* 设置当前元素与父元素中线对齐 */
    }

    .hint .message {
      display: inline;
      font-size: 12px;
      color: #333;
    }
  style>
head>

<body>
  <div class="register">
    <div class="pass">
      <label>
        <img src="img/no_eye.png" alt="" id="eye">
      label>
      <input type="password" id="pass" maxlength="15">
    div>
    <div class="hint">
      <span>*span>
      <p class="message">请输入6~12位密码p>
    div>
  div>
  <script>
    //获取元素
    var eye = document.querySelector('#eye');
    var pass = document.querySelector('#pass');
    var span = document.querySelector('span');
    var message = document.querySelector('.message');
    var flag = 0;
    //注册监听事件
    eye.addEventListener('click', function () {
      if (flag == 0) {    // 通过flag判断小眼睛的关合状态,以此改变输入框的类型
        pass.type = 'text';
        eye.src = 'img/eye.png';  //此处的小眼睛图标搜集于iconfont
        flag = 1;
      } else {
        pass.type = 'password';
        eye.src = 'img/no_eye.png';
        flag = 0;
      }
    })
    pass.addEventListener('blur', function () {
      if (this.value.length < 6 || this.value.length > 12) {  //判断用户输入的密码位数是否符合条件并给出提示信息
        span.innerHTML = '';
        message.innerHTML = '输入有误,请输入6~12位密码!'
        message.style.color = 'red';
      } else {
        span.innerHTML = '√';
        span.style.color = 'green';
        message.innerHTML = '';
      }
    })
  script>
body>

html>

你可能感兴趣的:(javascript,前端)