本篇文章给大家通过代码示例来介绍 JS 实现随机五位数验证码. 有一定的参考价值, 有需要的朋友可以参考一下, 希望对大家有所帮助.
功能展示:
点击按钮, 随机生成数字 + 大小写字母验证码
代码如下, 复制即可使用:
- <!DOCTYPE html>
- <HTML>
- <head>
- <meta charset="UTF-8">
- <title>
- 随机生成验证码
- </title>
- </head>
- <style>
- /* 验证码 */ .upload-awrp { overflow: hidden; margin: 120px 0; } .code {
- font-family: Arial; font-style: italic; font-size: 30px; border: 0; padding:
- 2px 3px; letter-spacing: 3px; font-weight: bolder; float: left; cursor:
- pointer; width: 150px; height: 60px; line-height: 60px; text-align: center;
- vertical-align: middle; border: 1px solid #6D6D72; }
- </style>
- <body>
- <!-- 随机验证码 -->
- <div id="check-code" style="overflow: hidden;">
- <div class="code" id="data_code">
- </div>
- </div>
- <script src="http://libs.baidu.com/jquery/1.9.1/jquery.js">
- </script>
- <script type="text/javascript">
- $.fn.code_Obj = function(o) {
- var _this = $(this);
- var options = {
- code_l: o.codeLength,
- // 验证码长度
- codeChars: [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'],
- codeColors: ['#f44336', '#009688', '#cddc39', '#03a9f4', '#9c27b0', '#5e4444', '#9ebf9f', '#ffc8c4', '#2b4754', '#b4ced9', '#835f53', '#aa677e'],
- code_Init: function() {
- var code = "";
- var codeColor = "";
- var checkCode = _this.find("#data_code");
- for (var i = 0; i < this.code_l; i++) {
- var charNum = Math.floor(Math.random() * 52);
- code += this.codeChars[charNum];
- }
- for (var i = 0; i < this.codeColors.length; i++) {
- var charNum = Math.floor(Math.random() * 12);
- codeColor = this.codeColors[charNum];
- }
- console.log(code);
- if (checkCode) {
- checkCode.CSS('color', codeColor);
- checkCode.className = "code";
- checkCode.text(code);
- checkCode.attr('data-value', code);
- }
- }
- };
- options.code_Init(); // 初始化验证码
- _this.find("#data_code").bind('click',
- function() {
- options.code_Init();
- });
- };
- $('#check-code').code_Obj({
- codeLength: 5
- });
- </script>
- </body>
- </HTML>
动态效果图:
更多 web 开发 https://www.html.cn/ 知识, 请查阅 HTML 中文网 !!
来源: http://www.css88.com/web/javascript/17508.html