利用js随机生成四位颜色各不相同的验证码
<body onload="dianji()">
<!--随机数字-->
<p>
<span></span>
<span></span>
<span></span>
<span></span>
</p>
<!--按钮-->
<input type="button" id="srk" onclick="dianji()"/ value="看不清">
<script>
var srk;//声明全局变量
var span=document.getElementsByTagName('span');//获取span
//点击时调用函数
function dianji(){
//声明变量类型为string
var srk='';
//获取id声明
var srkV=document.getElementById('srk');
//随机数所属数组
var shuzu=new Array(1,2,3,4,5,6,7,8,9,0,
"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");
//for循环来得到4位数字
for(var i=0;i<4;i++){
//从数组shuzu中选取四位随机数
var num=parseInt(Math.random()*shuzu.length);
//选取的每个随机数声明为srk
srk=shuzu[num]
//将srk输入到span标签中,并使之随循环进行
span[i].innerHTML=srk;
//将span标签中的字体颜色设置为调用函数randomColor()
span[i].style.color=randomColor();
}
}
</script>
</body>
分装函数
//随机颜色函数
function randomColor(){
var c1=parseInt(Math.random()*256);
var c2=parseInt(Math.random()*256);
var c3=parseInt(Math.random()*256);
var rgb="rgb("+c1+","+c2+","+c3+")";
return rgb;
}