JavaScript实现随机抽奖功能

 通过数组存储抽奖号码,点击按钮实现名字/号码的滚动,点击停止即可实现抽奖功能

设置一个定时器,使用random方法随机获取号码,当点击按钮时去掉计时器实现暂停功能。

思路解析:

(1)抽奖功能的名字滚动可以使用定时器都是获取名单中的数据;

(2)为了保证随机性,可使用random()方法随机获取名单中的数据,以此达到随机滚动的效果;

(3)点击抽奖的功能可以通过关闭定时器实现,让屏幕只显示以此random后的数据,实现获取抽奖结果。

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<title>Document</title>
		<style>
		body{
			/* background: url(img/allOfUs.jpg); */
			background-size:100%;
			background-attachment: fixed;
		}
		h1{
			font-size: 50px;
			font-family: "courier new";
			color: aqua;
		}

		.container{
			width: 70%;
			height: 450px;
			border: 1px solid #ccc;
			margin: 100px  auto;
			padding: 5px;
			align-items: center;
			line-height: 50px;
			text-align: center;
			backdrop-filter: blur(10px);
		}
		.show_name{
			align-items: center;
			border: #00FFFF 1px solid;
			width: 250px;
			height: 120px;
			line-height: 80px;
			text-align: center;
			margin: auto;
		}
		h2{
			font-size: 30px;
		}
		.choose{
			margin-top: 15px;
		}
		input{
			width: 80px;
			height: 40px;
			margin: 10px;
			border: aliceblue;
			border-radius: 10px;
			font-size: 17px;
			color: brown;
		}
		</style>
	</head>
	<body>
		<div class="container" >
			<h1>大&nbsp; &nbsp;奖&nbsp; &nbsp;得&nbsp; &nbsp;主</h1>
			<div  class="show_name">
				<h2 id="title">大&nbsp;家</h2>
			</div>
			<div class="choose">
				<input id="but" type="button"  value="开 始"/>
				
			</div>

		</div>


		<script>
		    var flag=0;
			var arr = [
				'阿呷', '曾&nbsp;各','陈羽','陈&nbsp;吧','丁发', '杜子发', '严&nbsp;辉'
				,'洪发','曾富','真帅','帅得很','好帅','这么帅']
			// 通过id拿到h2的标签
			var title = document.getElementById('title')
			var timer = null 
			function start() {
				timer = setInterval(function() {
					var index = Math.floor(Math.random() * arr.length)
					// 把index对应的数组的内容放到h2标签里面
					title.innerHTML = arr[index]
				}, 100)
			}

			function end() {
				// 通过timer来控制开始按钮
				clearInterval(timer)
			}
			but.onclick=function(){
				if(flag==0){
					flag++;
					but.value='停止';
					start();
					
					
				}else{
					flag--;
					but.value='开始';
					end();
					
				}
			}
		</script>
	</body>
</html>

 效果图:

开始界面:

 滚动界面效果:

 

猜你喜欢

转载自blog.csdn.net/NXBBC/article/details/125347952