简单模拟网页的随机数字验证码,效果图如下:
html代码:
1 <div id="content"> 2 <div class="left"> 3 <input type="text" class="txt" id="in"> 4 </div> 5 <div class="right"> 6 <span id="code"></span> 7 <input type="submit" id="btn" value="验证"> 8 </div> 9 </div>
css样式:
1 <style type="text/css"> 2 #code{ 3 display: inline-block; 4 color:blue; 5 font-weight: bolder; 6 background-color: #D9799B; 7 font-size: 20px; 8 text-align: center; 9 border:none; 10 height: 30px; 11 width: 100px; 12 margin-right: 10px; 13 letter-spacing: 4px; 14 line-height: 30px; 15 } 16 #btn{ 17 display: inline-block; 18 height: 30px; 19 width: 50px; 20 } 21 .txt{ 22 display: inline-block; 23 height: 30px; 24 width: 160px; 25 line-height: 30px; 26 } 27 div .right{ 28 margin-top: 10px; 29 } 30 </style>
javascript代码:
1 <script type="text/javascript"> 2 var array=[1,2,3,4,5,6,7,8,9,0]; 3 window.onload=function(){ 4 var iden=document.getElementById("code"); 5 var btn=document.getElementById("btn"); 6 iden.innerHTML=randomNumber(array);//获取验证码框的随机值 7 iden.addEventListener("click",function(){ //当点击验证码框时变换验证码 8 var arr=randomNumber(array); 9 iden.innerHTML=arr; 10 }); 11 btn.addEventListener("click",function(){ 12 var txt=document.getElementById("in"); 13 if(txt.value==parseInt(iden.innerHTML)){ 14 alert("验证成功"); 15 } 16 else{ 17 alert("验证码填写不正确!"); 18 iden.innerHTML=randomNumber(array); 19 txt.value=""; 20 } 21 22 }); 23 }; 24 function randomNumber(arr){ 25 var arr1=[]; 26 var n=0; 27 for(var i=0;i<4;i++){ //产生随机数值 28 n=Math.floor(Math.random()*10); 29 arr1[i]=arr[n]; 30 } 31 return arr1.toString().replace(/,/g,""); //返回一个字符串 32 } 33 34 </script>
代码可能优化的不太好,还请多多指教!
时间: 2024-11-12 18:10:51