js自制验证码

100 阅读1分钟

方法一:

<body>
  <p>验证码:</p>
  <div id="login" onclick="change()">
    <a href="#" rel="external nofollow"></a>
  </div>

  <script>
    function getCode(n) {
      var all = "azxcvbnmsdfghjklqwertyuiopZXCVBNMASDFGHJKLQWERTYUIOP0123456789";
      var b = "";
      for (var i = 0; i < n; i++) {
        var index = Math.floor(Math.random() * 62);
        b += all.charAt(index);
      }
      return b;
    };

    function change() {
      document.getElementById("login").innerHTML = getCode(5);
    }
    window.onload = change;

  </script>
</body>

方法二:

<body>
  <div id="verification-code" onselectstart="return false;"></div>
  <script>
    function Verification(options) {
      this.height = options.height || 40  //默认值
      this.width = options.width || 100  //默认值
      this.el = options.el
      this.ele = document.querySelector(this.el)

      this.init()
    }

    Verification.prototype.init = function () {
      this.setStyle()
      this.getCode()
      this.myClick()
    }

    Verification.prototype.setStyle = function () {
      this.ele.style.width = this.width + 'px'
      this.ele.style.height = this.height + 'px'
      this.ele.style.backgroundColor = '#ccc'
      this.ele.style.lineHeight = this.height + 'px'
      this.ele.style.textAlign = 'center'
      this.ele.style.color = 'blue'
      this.ele.style.fontSize = '26px'
    }

    Verification.prototype.getCode = function () {
      const codeArr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f', 'g',
        'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

      let codeStr = ''
      let len = codeArr.length - 1

      for (let i = 0; i < 3; i++) {
        // 这里为什么要*codeArr.length-1呢?因为Math.random()生成[0, 1]之间的数,如果*codeArr.length的话,会出现codeArr[codeArr.length]
        let k = Math.round(Math.random() * len)
        // Math.round:四舍五入
        codeStr += codeArr[k]
      }
      this.ele.innerText = codeStr
    }

    Verification.prototype.myClick = function () {
      const that = this
      this.ele.addEventListener('click', function () {
        that.getCode()
      })
    }


    const verfication = new Verification({
      el: '#verification-code',
      width: 200,
      height: 80
    })
  </script>
</body>