今天的案例,效果如下:

这个案例的实现其实没有很多难点,让我们一起来看看吧~
html和css的实现,在这里就不做解释啦,可以比对下面的代码自己实现一下,注意一下细节就好了
接着咱们来看看js的实现:
我们需要做到的有两点:
- 实现验证码的随机产生,使其在==页面刷新和点击更换==时能够生成
- 实现输入字符串和验证码的比较
==第一点呢==,我们需要用到for循环和Math.round(Math.random()*n),使得在每一次循环中可以产生随机数字
==第二点呢==,我们只需要通过input.value来获得用户输入的字符串,然后将其与之前随机产生的字符串进行比较即可(使用===)
其他的细节可以去代码中查看哦
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
| <!DOCTYPE html> <html lang="en">
<head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> .container{ width: 400px; height: 100px; margin:100px auto; background-color: hsla(180, 73%, 78%, 0.199); border-radius: 20px; text-align: center; padding: 20px; } #check{ display: inline-block; width: 100px; height: 30px; text-align: center; background-color: rgba(128, 128, 128, 0.158); color:blue; font-size:26px; font-style: italic; letter-spacing: 2px; font-family:Arial, Helvetica, sans-serif; margin-bottom: 10px; } .ma{ margin-bottom: 12px; }
</style> </head>
<body> <div class="container"> <div> <span id="check">adf34y</span> <a href="#" id="checka">看不清换一张</a> </div> <div class="ma"> <label for="zheng">验证码</label> <input type="text" id="zheng"> </div> <button id="btn">确定</button> </div>
<script> let sum=[0,1,2,3,4,5,6,7,8,9,'a','b','c','d','e','f']; var check=document.getElementById("check"); var code; function fun(){ let str=""; for(let i=0;i<6;i++){ let pos=Math.round(Math.random()*15); str+=sum[pos]; } check.innerHTML=str; return str; }
window.onload=function(){ code=fun(); }
let checka=document.getElementById("checka"); checka.onclick=function(){ code=fun(); } let btn=document.getElementById("btn"); btn.onclick=function(){ let t=document.getElementById("zheng").value; console.log(t) if(t==code){ alert("正确"); code=fun(); document.getElementById("zheng").value=""; } else{ alert("错误"); document.getElementById("zheng").value=""; } }
</script> </body>
</html>
|