css样式:<style type="text/css"> ???????????/*给验证码设一个盒子*/ ???????????#yzm{ ???????????????width: 120px; ???????????????height: 50px; ???????????????text-align: center; ???????????????background: #ccc; ???????????????float: left; ???????????} ???????????span{ ???????????????font-size: 20px; ???????????????line-height: 50px; ???????????} ???????????/*按钮*/ ???????????button{ ???????????????width: 100px; ???????????????height: 50px; ???????????}</style>
html代码:<body onload=‘yanzhengma()‘> ???<!--在页面加载时就执行这个函数--> ???<div id="yzm"> ????????<span></span> ????????<span></span> ????????<span></span> ????????<span></span> ???</div> ???<!--点击事件--> ???<button onclick="yanzhengma()">刷新</button></body>
js代码:<script type="text/javascript"> ?????????????//先写出一些需要随机的数字及字母 ???????????var shu = (‘1234567890qwertyuioplkjhgfdsazxcvbnmQAZWSXEDCRFVTGBYHNUJMIKOLP‘); ???????????//获取span ???????????var span = document.getElementsByTagName("span"); ???????????//定义一个函数为yanzhengma() ???????????function yanzhengma(){ ???????????????var yzm=" "; ???????????????//想要几个循环几个数值 ???????????????for(i=0;i<4;i++){ ???????????????????//随机Math.random()出的值乘以数组的长度,取出的值为数组的下标 ???????????????????var num = parseInt(Math.random() * shu.length); ???????????????????//取出shu中的值,利用上面取出的下标num,此时取出的是数组中的值 ???????????????????yzm = shu[num]; ???????????????????//把随机取到的值通过innerHTML在页面上 ???????????????????span[i].innerHTML=yzm; ???????????????????//把随机出的值通过style.color赋予颜色 ,Color()是自己封装的一个随机颜色函数 ??????????????????????span[i].style.color=color(); ???????????????} ???????????} ???</script>
颜色封装的代码:/*封装Color*/ ???function color(){ ???????var color = "rgb(" + Math.floor(Math.random() * 255) + "," + Math.floor(Math.random() * 255) + "," + Math.floor(Math.random() * 255) + ")"; ???????return color; ???}
注意:封装在写完的时候千万千万记住要把它引入HTML中!!
效果:
js随机生成验证码及其颜色
原文地址:https://www.cnblogs.com/zxnn/p/8196746.html