今天心血来潮搜索了下验证码的实现方式,仿照网上一个6位字符型的验证码实现了一个100以内算术题式的验证码。代码如下,备用:
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
- <title>验证码</title>
- <style type="text/css">
- .nocode {
- width: 100px;
- height: 25px;
- }
- .code {
- background: url(code_bg.jpg) repeat;
- color: #ff0000;
- font-family: Tahoma, Geneva, sans-serif;
- font-style: italic;
- font-weight: bold;
- text-align: center;
- width: 100px;
- height: 25px;
- cursor: pointer;
- }
- .input {
- width: 100px;
- }
- </style>
- <script type="text/javascript" src="jquery.js"></script>
- <script type="text/javascript">
- $(function() {
- var code = 9999;
- $(".input").focus(function(){
- $(this).attr("value", "");
- var num1 = Math.floor(Math.random() * 100);
- var num2 = Math.floor(Math.random() * 100);
- code = num1 + num2;
- $("#code").html(num1 + "+" + num2 + "=?");
- if ($("#code").hasClass("nocode")) {
- $("#code").removeClass("nocode");
- $("#code").addClass("code");
- }
- });
- $("#check").click(function(){
- if ($(".input").attr("value") == code && code != 9999) {
- alert("Pass!");
- } else {
- alert("Wrong code!");
- }
- });
- });
- </script>
- </head>
- <body>
- <input type="text" class="input" />
- <div id="code" class="nocode"></div>
- <button id="check">验证</button>
- </body>
- </html>
效果如下:
上述实现主要还是基于jQuery,其实也可以不用。JavaScript 1.6新添加了一系列函数,其中就包含document.querySelector和document.querySelectorAll。这两个函数的作用与jQuery的元素选择器如出一辙,即通过传入类似于 ".class" 、 "#id" 等这样的字符串选择符来获取元素;区别在于 querySelector 函数获取的是符合选择符的第一个DOM元素,而 querySelectorAll 函数获取的是符合选择符的DOM元素数组。获取到元素之后,就可以通过相应的事件(如onfocus、onclick等)来操作数据了。
另外,验证码的元素除了用<div>以外,还可能使用<input type="text">,只不过需要对其做一定的处理:如去掉输入框的边框(border: none),设置为只读(readonly)。
最后附上验证码的背景图片 code_bg.jpg :