随机验证码的生成

开发工具与关键技术:DW JavaScript
作者:Mr_肖先生
撰写时间:2019年2月18日

在JavaScript中,有个随机生成数字的函数叫 Math.random(),它能生成0~1之间的数字,下面我给大家简单列了个例子:

<head>
<meta charset="utf-8">
<title>随机验证码的生成</title>
</head>
	<style>
		#number{
			width:130px;
			height: 30px;
			text-align: center;
			line-height: 30px;
			background: pink;
			margin: 10px 5px 0px 50px;
			cursor: pointer;
			float: left;
		}
		#get{
			margin: 13px 5px 0px 0px;
		}
	</style>
<body>
	<div id="number"></div>
	<button id="get">点击获取验证码</button>
</body>

这里是一些基本样式和布局,下面的JavaScript才是重点,让我们看一下

var get=document.getElementById("get");
	get.onclick=function(){
		array();
	};
	function array(){
		first = [0,1,2,3,4,5,6,7,8,9];
		second = [0,1,2,3,4,5,6,7,8,9];
		third = [0,1,2,3,4,5,6,7,8,9];
		fourth = [0,1,2,3,4,5,6,7,8,9];
		var a = String(first[Math.floor(Math.random()*first.length)]);
		var b = String(second[Math.floor(Math.random()*second.length)]);
		var c = String(third[Math.floor(Math.random()*third.length)]);
		var d = String(fourth[Math.floor(Math.random()*fourth.length)]);
		var number=document.getElementById("number");
		number.innerHTML=a+b+c+d;
	}

首先我们先定义一个数组函数,里面有4个数组,这4个数组内容基本一样,生成的都是随机数,这个其中的核心就是Math.random()了,随机生成0~1的数字,然后乘于数组长度,string是将数字类型转换成字符串类型,Math.floor是将小数转换成整数,最后获取到要显示出来的div,给它赋值就ok了,我们再给按钮一个点击事件,调用一下这个数组函数,效果如下:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_44505797/article/details/87610150