1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 <style type="text/css"> 7 *{ 8 margin:0; 9 padding:0; 10 } 11 span{ 12 13 height: 20px; 14 line-height: 20px; 15 text-align: center; 16 background: gray; 17 color: #f0f0f0; 18 } 19 div{ 20 width:100px; 21 height: 100px; 22 border:1px solid red; 23 } 24 </style> 25 <script type="text/javascript"> 26 window.onload = function () { 27 //随机生成四位数字的验证码 28 var t = parseInt(Math.random()*8999+1000); 29 var spanNode = document.getElementsByTagName("span")[0]; 30 spanNode.innerHTML = t; 31 //随机生成含有字母的验证码 32 //注意toString括号里的值,可以不写,不写默认的是10,小于10只会出现数字。大于10会出现字母 33 var b = Math.random().toString(36).substr(2); 34 var span1Node = document.getElementsByTagName("span")[1]; 35 span1Node.innerHTML =b; 36 //利用随机函数使颜色随机变化 37 var r =Math.round(Math.random()*256)%255; 38 var g =Math.round(Math.random()*256)%255; 39 var b =Math.round(Math.random()*256)%255; 40 var rgbB = "rgb("+r+","+b +","+g+")"; 41 document.body.style.background =rgbB; 42 } 43 //随机产生数组里包含的验证码 44 //randomFlag表示是否随机 45 //min随机字符的最小长度 46 //max随机字符的最大长度 47 function randomWord(randomFlag, min, max){ 48 var str = "", 49 range = min, 50 arr = ['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']; 51 // 随机产生 52 if(randomFlag){ 53 range = Math.round(Math.random() * (max-min)) + min; 54 } 55 for(var i=0; i<range; i++){ 56 pos = Math.round(Math.random() * (arr.length-1)); 57 str += arr[pos]; 58 } 59 return str; 60 } 61 var g = randomWord(true, 3, 8); 62 document.write(g); 63 </script> 64 </head> 65 <body> 66 <form action=""> 67 <h3>产生四位数字的随机验证码</h3> 68 <span></span> 69 <input type="submit" value="换一组"> 70 <h3>产生包含字母的随机验证码</h3> 71 <span></span> 72 <input type="submit" value="换一组"> 73 </form> 74 </body> 75 </html>