首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >js验证码

js验证码

作者头像
老猫-Bond
发布2023-12-11 20:14:41
发布2023-12-11 20:14:41
3.3K0
举报
文章被收录于专栏:前端大全前端大全

html+css+js实现的验证码

js验证码

HTML

代码语言:javascript
复制

<div class="codediv">
  <div class="code" id="codes" onclick="createCode();"></div>
  <input name="code" type="text" maxlength="4" class="code-input" required placeholder="请输入验证码">
</div>

CSS

代码语言:javascript
复制

/* 我的css */
.codediv{
  display:flex;
  flex-direction: row;
  justify-content: flex-start;
  margin-right: 5px;
}

.code {
  margin-right: 3px;
  background: url(code_bg.png);//图片地址:https://a.biugle.cn/setcodes/code_bg.png
  font-family: Arial;
  font-style: italic;
  color: white;
  font-size: 17px;
  border: 0;
  border-radius: 5px;
  padding: 1px 3px 1px 5px;
  letter-spacing: 6px;
  font-weight: bolder;
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  cursor: pointer;
  width: 70px;
  height: 21px;
  line-height: 21px;
  text-align: center;
  vertical-align: middle;
}

.code-input{
  color: #4876ff;
  border: 1px solid #777;
  box-sizing: border-box;
  padding-left: 5px;
  padding-right: 5px;
  line-height: 15px;
  font-size: 15px;
  width: 121px;
  border-radius: 5px;
  outline: none;
}

JS

代码语言:javascript
复制

/**
 * 生成验证码,CSS样式自行设计。
 */
var code;
function createCode() {
  code = "";
  var codeLength = 4;//验证码的长度
  var checkCode = document.querySelector("#codes");
  var codeChars = new Array(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', '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', '贺');//所有候选组成验证码的字符,可以用中文。
  for (var i = 0; i < codeLength; i++) {
    var charNum = Math.floor(Math.random() * 52);
    code += codeChars[charNum];
  }
  if (checkCode) {
    checkCode.className = "code";
    checkCode.innerHTML = code;
  }
}
/* 记得先将输入的内容全转为大写或者小写,再进行验证。 */
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019-05-05,如有侵权请联系 cloudcommunity@tencent.com 删除
目录
  • js验证码
    • HTML
    • CSS
    • JS
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档