JavaScript编写带旋转+线条干扰的验证码脚本实例


Posted in Javascript onMay 30, 2016

基础版

从我们平时上网的经验来看,验证码一般是四位,由数字和字母组成。
那么接下来楼主将带领大家一步步用JavaScript做出一个验证码脚本!
先给出成品,方便大家理解:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
   <style>
    #securityCode{
      background-color: #008000;
      width:70px;
      height:30px;
      font-family: '楷体', serif;
      font-size: 20px;
      color:white;
    }
  </style>
  <script language="JavaScript" type="text/javascript">
   function createCode(){
      var code=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');
      var codeNumber;
      securityCode="";//全局变量,方便后续验证
      for(var i=0;i<4;i++){
        codeNumber=Math.floor(Math.random()*36);
        securityCode+=code[codeNumber];
      }
      document.getElementById("securityCode").value=securityCode;
    }
    function verify(){
      var enterCode=document.getElementById("enterCode").value;
      if(enterCode.toUpperCase()==securityCode){
        alert("输入正确,通过验证!");
      }
      else{
        enterCode.value="";
        createCode();
      }
    }
  </script>
    <title>Jizhen Tan</title>
</head>
<body onLoad="checkCookie()" >
   <input type="text" id="enterCode"><br/>
   <input type="button" id="securityCode"  onclick="createCode()">
   <a href="###" onclick="createCode()">看不清楚</a><br/>
   <input type="button" style="background-color: #0099FF; font-size: 20px;"value="验证" onclick="verify()">
</body>
</html>

1.既然是四位验证码,我们的思路就要打开一些了,首先我们需要一个数组来储存字母和数字。

var code=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');

2.然后我们需要让它随机显示数组中的元素,这里我们建立一个codeNumber变量来随机显示的数字,但我们需要的是四位验证码,而现在数组中的元素都是单个的,怎么办呢?简单!我们再建立一个securityCode变量来储存数组中的元素不就得了。代码如下:

var codeNumber;
      securityCode="";//全局变量,方便后续验证
      for(var i=0;i<4;i++){
        codeNumber=Math.floor(Math.random()*36);
        securityCode+=code[codeNumber];
      }

可以看出此时securityNumber变量储存的就是一个四位随机验证码
3.好了,经过简单的两步,我们就得到了四位验证码。我们将它放在一个createCode函数中。

function createCode(){
      var code=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');
      var codeNumber;
      securityCode="";//全局变量,方便后续验证
      for(var i=0;i<4;i++){
        codeNumber=Math.floor(Math.random()*36);
        securityCode+=code[codeNumber];
      }
      document.getElementById("securityCode").value=securityCode;
    }

4.接下来我们创建一个验证机制:

function verify(){
      var enterCode=document.getElementById("enterCode").value;
      if(enterCode.toUpperCase()==securityCode){
        alert("输入正确,通过验证!");
      }
      else{
        enterCode.value="";
        createCode();
      }
    }

5.小小修饰下验证码:

<style>
    #securityCode{
      background-color: #008000;
      width:70px;
      height:30px;
      font-family: '楷体', serif;
      font-size: 20px;
      color:white;
    }
  </style>

进阶:进一步阻止机器人的高级技巧
接触的大部分项目中,验证码一直都是后台干的事,这两天正好有一个页面需要验证码,第时间想着后台实现,但突然转念一想大部分项目貌似对安全性要求不是很高,又要求有点阻止机器人的技巧,于是就用前端写了一个验证码。并利用CSS3的transform属性里的rotate设置旋转,再随机弄点干扰线,最后为了在所有DOM节点的上边加一层opacity=0的DIV,一个前端验证码就出来了。

JavaScript编写带旋转+线条干扰的验证码脚本实例

vCode代码:

(function(){
  var randstr = function(length){
    var key = {
 
      str : [
        'a','b','c','d','e','f','g','h','i','j','k','l','m',
        'o','p','q','r','s','t','x','u','v','y','z','w','n',
        '0','1','2','3','4','5','6','7','8','9'
      ],
 
      randint : function(n,m){
        var c = m-n+1;
        var num = Math.random() * c + n;
        return Math.floor(num);
      },
 
      randStr : function(){
        var _this = this;
        var leng = _this.str.length - 1;
        var randkey = _this.randint(0, leng);
        return _this.str[randkey];
      },
 
      create : function(len){
        var _this = this;
        var l = len || 10;
        var str = '';
 
        for(var i = 0 ; i<l ; i++){
          str += _this.randStr();
        }
 
        return str;
      }
 
    };
 
    length = length ? length : 10;
 
    return key.create(length);
  };
 
  var randint = function(n,m){
    var c = m-n+1;
    var num = Math.random() * c + n;
    return Math.floor(num);
  };
 
  var vCode = function(dom, options){
    this.codeDoms = [];
    this.lineDoms = [];
    this.initOptions(options);
    this.dom = dom;
    this.init();
    this.addEvent();
    this.update();
    this.mask();
  };
 
  vCode.prototype.init = function(){
    this.dom.style.position = "relative";
    this.dom.style.overflow = "hidden";
    this.dom.style.cursor = "pointer";
    this.dom.title = "点击更换验证码";
    this.dom.style.background = this.options.bgColor;
    this.w = this.dom.clientWidth;
    this.h = this.dom.clientHeight;
    this.uW = this.w / this.options.len;
  };
 
  vCode.prototype.mask = function(){
    var dom = document.createElement("div");
    dom.style.cssText = [
      "width: 100%",
      "height: 100%",
      "left: 0",
      "top: 0",
      "position: absolute",
      "cursor: pointer",
      "z-index: 9999999"
    ].join(";");
 
    dom.title = "点击更换验证码";
 
    this.dom.appendChild(dom);
  };
 
  vCode.prototype.addEvent = function(){
    var _this = this;
    _this.dom.addEventListener("click", function(){
      _this.update.call(_this);
    });
  };
 
  vCode.prototype.initOptions = function(options){
 
    var f = function(){
      this.len = 4;
      this.fontSizeMin = 20;
      this.fontSizeMax = 48;
      this.colors = [
        "green",
        "red",
        "blue",
        "#53da33",
        "#AA0000",
        "#FFBB00"
      ];
      this.bgColor = "#FFF";
      this.fonts = [
        "Times New Roman",
        "Georgia",
        "Serif",
        "sans-serif",
        "arial",
        "tahoma",
        "Hiragino Sans GB"
      ];
      this.lines = 8;
      this.lineColors = [
        "#888888",
        "#FF7744",
        "#888800",
        "#008888"
      ];
 
      this.lineHeightMin = 1;
      this.lineHeightMax = 3;
      this.lineWidthMin = 1;
      this.lineWidthMax = 60;
    };
 
    this.options = new f();
 
    if(typeof options === "object"){
      for(i in options){
        this.options[i] = options[i];
      }
    }
  };
 
  vCode.prototype.update = function(){
    for(var i=0; i<this.codeDoms.length; i++){
      this.dom.removeChild(this.codeDoms[i]);
    }
    for(var i=0; i<this.lineDoms.length; i++){
      this.dom.removeChild(this.lineDoms[i]);
    }
    this.createCode();
    this.draw();
  };
 
  vCode.prototype.createCode = function(){
    this.code = randstr(this.options.len);
  };
 
  vCode.prototype.verify = function(code){
    return this.code === code;
  };
 
  vCode.prototype.draw = function(){
    this.codeDoms = [];
    for(var i=0; i<this.code.length; i++){
      this.codeDoms.push(this.drawCode(this.code[i], i));
    }
 
    this.drawLines();
  };
 
  vCode.prototype.drawCode = function(code, index){
    var dom = document.createElement("span");
 
    dom.style.cssText = [
      "font-size:" + randint(this.options.fontSizeMin, this.options.fontSizeMax) + "px",
      "color:" + this.options.colors[randint(0, this.options.colors.length - 1)],
      "position: absolute",
      "left:" + randint(this.uW * index, this.uW * index + this.uW - 10) + "px",
      "top:" + randint(0, this.h - 30) + "px",
      "transform:rotate(" + randint(-30, 30) + "deg)",
      "-ms-transform:rotate(" + randint(-30, 30) + "deg)",
      "-moz-transform:rotate(" + randint(-30, 30) + "deg)",
      "-webkit-transform:rotate(" + randint(-30, 30) + "deg)",
      "-o-transform:rotate(" + randint(-30, 30) + "deg)",
      "font-family:" + this.options.fonts[randint(0, this.options.fonts.length - 1)],
      "font-weight:" + randint(400, 900)
    ].join(";");
 
    dom.innerHTML = code;
    this.dom.appendChild(dom);
 
    return dom;
  };
 
  vCode.prototype.drawLines = function(){
    this.lineDoms = [];
    for(var i=0; i<this.options.lines; i++){
      var dom = document.createElement("div");
 
      dom.style.cssText = [
        "position: absolute",
        "opacity: " + randint(3, 8) / 10,
        "width:" + randint(this.options.lineWidthMin, this.options.lineWidthMax) + "px",
        "height:" + randint(this.options.lineHeightMin, this.options.lineHeightMax) + "px",
        "background: " + this.options.lineColors[randint(0, this.options.lineColors.length - 1)],
        "left:" + randint(0, this.w - 20) + "px",
        "top:" + randint(0, this.h) + "px",
        "transform:rotate(" + randint(-30, 30) + "deg)",
        "-ms-transform:rotate(" + randint(-30, 30) + "deg)",
        "-moz-transform:rotate(" + randint(-30, 30) + "deg)",
        "-webkit-transform:rotate(" + randint(-30, 30) + "deg)",
        "-o-transform:rotate(" + randint(-30, 30) + "deg)",
        "font-family:" + this.options.fonts[randint(0, this.options.fonts.length - 1)],
        "font-weight:" + randint(400, 900)
      ].join(";");
      this.dom.appendChild(dom);
 
      this.lineDoms.push(dom);
    }
  };
 
  this.vCode = vCode;
 
}).call(this);

用法:

//container 为 验证码的DOM节点
var code = new vCode(container);
 
// 验证是否正确
// inputCode为用户输入的验证码
code.verify(inputCode); // return true or false
Javascript 相关文章推荐
Jquery倒数计时按钮setTimeout的实例代码
Jul 04 Javascript
JavaScript 命名空间 使用介绍
Aug 29 Javascript
禁止选中文字兼容IE、Chrome、FF等
Sep 04 Javascript
老生常谈 关于JavaScript的类的继承
Jun 24 Javascript
js实现图片淡入淡出切换简易效果
Aug 22 Javascript
jQuery异步提交表单的两种方式
Sep 13 Javascript
easyui form validate总是返回false的原因及解决方法
Nov 07 Javascript
详谈表单重复提交的三种情况及解决方法
Aug 16 Javascript
微信小程序之侧边栏滑动实现过程解析(附完整源码)
Aug 23 Javascript
vuejs element table 表格添加行,修改,单独删除行,批量删除行操作
Jul 18 Javascript
vue $router和$route的区别详解
Dec 02 Vue.js
如何在CocosCreator里画个炫酷的雷达图
Apr 16 Javascript
Bootstrap编写导航栏和登陆框
May 30 #Javascript
Bootstrap+jfinal退出系统弹出确认框的实现方法
May 30 #Javascript
Bootstrap+jfinal实现省市级联下拉菜单
May 30 #Javascript
基于Bootstrap里面的Button dropdown打造自定义select
May 30 #Javascript
BootStrap下jQuery自动完成的样式调整
May 30 #Javascript
JavaScript常用判断写法大全(推荐)
May 30 #Javascript
基于AngularJs + Bootstrap + AngularStrap相结合实现省市区联动代码
May 30 #Javascript
You might like
Yii PHP Framework实用入门教程(详细介绍)
2013/06/18 PHP
php实现把数组按指定的个数分隔
2014/02/17 PHP
PHP中获取时间的下一周下个月的方法
2014/03/18 PHP
Thinkphp中volist标签mod控制一定记录的换行BUG解决方法
2014/11/04 PHP
javascript基本语法分析说明
2008/06/15 Javascript
javascript的trim,ltrim,rtrim自定义函数
2008/09/21 Javascript
firebug的一个有趣现象介绍
2011/11/30 Javascript
js网页实时倒计时精确到秒级
2014/02/10 Javascript
jquery日历控件实现方法分享
2014/03/07 Javascript
jQuery如何取id有.的值一般的方法是取不到的
2014/04/18 Javascript
基于Jquery插件Uploadify实现实时显示进度条上传图片
2020/03/26 Javascript
解决vue组件props传值对象获取不到的问题
2019/06/06 Javascript
vue实现随机验证码功能(完整代码)
2019/12/10 Javascript
JavaScript arguments.callee作用及替换方案详解
2020/09/02 Javascript
[01:31:02]TNC vs VG 2019国际邀请赛淘汰赛 胜者组赛BO3 第一场
2019/08/22 DOTA
python3模块smtplib实现发送邮件功能
2018/05/22 Python
Python最小二乘法矩阵
2019/01/02 Python
python输出电脑上所有的串口名的方法
2019/07/02 Python
Python 正则表达式爬虫使用案例解析
2019/09/23 Python
wxpython多线程防假死与线程间传递消息实例详解
2019/12/13 Python
全面介绍python中很常用的单元测试框架unitest
2020/12/14 Python
Python的logging模块基本用法
2020/12/24 Python
举例详解CSS3中的Transition
2015/07/15 HTML / CSS
html5新增的定时器requestAnimationFrame实现进度条功能
2018/12/13 HTML / CSS
DogBuddy荷兰:找到你最完美的狗保姆
2019/04/17 全球购物
Elemental Herbology官网:英国美容品牌
2019/04/27 全球购物
新闻记者个人求职的自我评价
2013/11/28 职场文书
法人代表授权委托书
2014/04/08 职场文书
心理健康日活动总结
2014/05/08 职场文书
幼儿园健康教育方案
2014/06/14 职场文书
2014乡镇党政班子四风问题思想汇报
2014/09/14 职场文书
2014年学校体育工作总结
2014/12/08 职场文书
2015年教师个人业务工作总结
2015/10/23 职场文书
2016元旦主持人开场白
2015/12/03 职场文书
PyQt5 显示超清高分辨率图片的方法
2021/04/11 Python
golang 接口嵌套实现复用的操作
2021/04/29 Golang