JavaScript三种方法模拟双色球抽奖——使用标记、使用Interval、使用Timeout

本文介绍三种方法用于模拟双色球抽奖过程,包括使用标记、Interval和Timeout技术,详细展示了每种方法的实现步骤及运行效果,并对三种方法进行了对比总结。

本文使用三种方法模拟双色球抽奖。

公共页面:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>模拟双色球抽奖——不使用Interval和Timeout</title>

<style  type="text/css">
	.myStyle{
		height:35px;
		width:200px;
	}
</style>

</head>

<body>
<table align="center">
	<tr>
		<td><font size="2" color="blue">号码1</font></td>
		<td><font size="2" color="black">号码2</font></td>
		<td><font size="2" color="green">号码3</font></td>
		<td><font size="4" color="red"><b>特殊号码</b></font></td>
	</tr>
	<tr>
		<td><input style="color:blue;" class="myStyle" id="num1" type="text" value=""></td>
		<td><input style="color:black;" class="myStyle" id="num2" type="text" value=""></td>
		<td><input style="color:green;" class="myStyle" id="num3" type="text" value=""></td>
		<td><input style="color:red;font-size:20pt;height:35px;width:200px;" id="num4" type="text" value=""></td>
	</tr>
	<tr>
		<td colspan="2" align="right"><input style="height:35px;width:100px;" type="button" value="开始" onclick="control()"></td>
		<td colspan="2"><input style="height:35px;width:100px;" type="button" value="停止" onclick="stop()"></td>
	</tr>
	<tr>
		<td colspan="2" align="right">
			<font size="4" color="red"><b>抽奖结果:</b></font>
		</td>
		<td colspan="2">
			<input id="result" type="text" value="" class="myStyle">
		</td>
	<tr>
	
</table>
</body>
</html>


第一种方法:使用标记。


<script  type="text/javascript">

var running = false;

//控制开始或者暂停
function control(){
	if(document.getElementById("result").value == "changing") { 
		document.getElementById("result").value = "start"; 
		running = false;
		return; 
	}else if(document.getElementById("result").value == "stop"){
		running = false;
		return;
	}else{
		running = true;
		start();
	}
}
//
var num1;
var num2;
var num3;
var num4;

//开始抽奖
function start(){

	if(running){
		
		document.getElementById("result").value="changing"; 
		
		num1 = parseInt(Math.random() * 10);
		num2 = parseInt(Math.random() * 20);
		num3 = parseInt(Math.random() * 30);
		num4 = parseInt(Math.random() * 10);
		
		document.getElementById('num1').value = num1;
		document.getElementById('num2').value = num2;
		document.getElementById('num3').value = num3;
		document.getElementById('num4').value = num4;
		
		document.getElementById('result').value = num1 + "" + num2 + "" + num3 + "" + num4;
		
	
	}
}
//结束抽奖
function stop(){
	
	document.getElementById("result").value="stop";
	control();
	var result = num1 + "" + num2 + "" + num3 + "" + num4;
	document.getElementById('result').value = result;
	alert("恭喜您!您的中奖号码是:" + result);
}

var myTime = setInterval("start()", 100);

</script>


第二种方法:使用Interval。


<script  type="text/javascript">
//使用Interval

var timmerId = null;
var num1;
var num2;
var num3;
var num4;

function change(){

	num1 = parseInt(Math.random() * 10);
	num2 = parseInt(Math.random() * 20);
	num3 = parseInt(Math.random() * 30);
	num4 = parseInt(Math.random() * 10);
	
	document.getElementById('num1').value = num1;
	document.getElementById('num2').value = num2;
	document.getElementById('num3').value = num3;
	document.getElementById('num4').value = num4;
	
	document.getElementById('result').value = num1 + "" + num2 + "" + num3 + "" + num4;
}

//开始抽奖
function start(){
	timmerId = window.setInterval("change()", 100);
}
//结束抽奖
function stop(){

	window.clearInterval(timmerId);
	var result = num1 + "" + num2 + "" + num3 + "" + num4;
	document.getElementById('result').value = result;
	alert("恭喜您!您的中奖号码是:" + result);
}
</script>


第三种方法:使用Timeout。

<script  type="text/javascript">
//使用Timeout

var timmerId = null;
var num1;
var num2;
var num3;
var num4;

function change(){

	
	
	num1 = parseInt(Math.random() * 10);
	num2 = parseInt(Math.random() * 20);
	num3 = parseInt(Math.random() * 30);
	num4 = parseInt(Math.random() * 10);
	
	document.getElementById('num1').value = num1;
	document.getElementById('num2').value = num2;
	document.getElementById('num3').value = num3;
	document.getElementById('num4').value = num4;
	
	document.getElementById('result').value = num1 + "" + num2 + "" + num3 + "" + num4;
	
	start();
}

//开始抽奖
function start(){
	timmerId = window.setTimeout("change()", 100);
}
//结束抽奖
function stop(){

	window.clearTimeout(timmerId);
	var result = num1 + "" + num2 + "" + num3 + "" + num4;
	document.getElementById('result').value = result;
	alert("恭喜您!您的中奖号码是:" + result);
}

</script>

运行效果截图(界面有点丑,哈哈):




总结:


1.本文使用的三种方法均可达到相同的效果。核心就是随机函数和定时器函数。


2.第一种巧妙的使用了标记,点击开始或者停止后把控件的值改变,然后再进行判断,再进行相应的方法调用;第二种方法是定时器方法setInterval();和clearInterval();的使用,每隔一定的时间周期进行方法的调用;第三种方法是定时器方法setTimeout();和clearTimeout();的使用,由于只调用一次相应的方法,所以需要在产生随机数的方法里再次进行调用。


3.需要注意的是,定时器的方法需要配套使用。

4.第二种和第三种方法需要把页面上“停止”按钮的onclick改成"stop()"。


强烈推荐阅读:setTimeout和setInterval的使用



源码下载:点击此处





<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Treasure</title> <link rel="stylesheet" href="./baoxiangimg/treasure.css"> </head> <body> <header class="headerImg"> <img src="./baoxiangimg/logo.svg" alt="logo"> </header> <div class="pgOct"> <img src="./baoxiangimg/pgOct.png" alt="pgOct"> </div> <canvas id="particle-background"></canvas> <!-- 动态背景元素 --> <div class="bg-element bg-element-1"></div> <div class="bg-element bg-element-2"></div> <div class="bg-element bg-element-4"></div> <div class="container"> <div class="treasure-container"> <div class="treasure-box" id="treasureBox"> <div class="treasure-base"></div> <div class="prize coupon" id="prize">¥50</div> </div> </div> <div class="countdown-container"> <h6>Contagem regressiva:</h6> <div class="digit-container"> <div class="digit" id="tens-digit">3</div> </div> <div class="digit-container"> <div class="digit" id="ones-digit">0</div> </div> </div> <div class="prize-list"> <div class="prize-item"> <img src="./baoxiangimg/coupon.png" /> <h3>🎟️ Pegue seu<br />cupom agora!</h3> </div> <div class="prize-item"> <img src="./baoxiangimg/money.png" /> <h3>💰 Ganhe recompensas<br />em dinheiro!</h3> </div> <div class=" prize-item"> <img src="./baoxiangimg/play.png" /> <h3>🎁 Receba prêmios<br />incríveis!</h3> </div> <div class="prize-item"> <img src="./baoxiangimg/exquisite.png" /> <h3>🧰 Abra o baú do<br /> seu amigo!</h3> </div> </div> <div class="particles" id="particles"></div> </div> <div class="winners-container"> <h2 class="winners-title">🎉 Lista de vencedores 🎉</h2> <div class="winners-list" id="winnersList"> <!-- 中奖名单将通过JavaScript动态生成 --> </div> </div> <div class="modal" id="prizeModal"> <div class="modal-content"> <h2>Congratulations!</h2> <p>Você ganhou o prêmio listado:</p> <div class="modal-prize" id="modalPrize">Cupom de R $50</div> <p>Prêmio enviado para sua conta. Confira!</p> <div class="countdown" id="countdown">Página redirecionará em 2 segundos...</div> </div><img class="pointerImg" src="bg.png"> </div> <script> // 初始化背景粒子 const canvas1 = document.getElementById('particle-background'); const ctxs = canvas1.getContext('2d'); function resizeCanvas() { canvas1.width = window.innerWidth; canvas1.height = window.innerHeight; } window.addEventListener('resize',resizeCanvas); resizeCanvas(); // 动画函数 // 生成粒子数组 const particlesArr = []; const particleCount = 100; for (let i = 0; i < particleCount; i++) { particlesArr.push({ x: Math.random() * window.innerWidth, y: Math.random() * window.innerHeight, radius: Math.random() * 2 + 1, vx: (Math.random() - 0.5) * 0.7, vy: (Math.random() - 0.5) * 0.7 }); } function animateParticles() { ctxs.clearRect(0,0,canvas1.width,canvas1.height); particlesArr.forEach(p => { p.x += p.vx; p.y += p.vy; if (p.x < 0 || p.x > canvas1.width) p.vx *= -1; if (p.y < 0 || p.y > canvas1.height) p.vy *= -1; ctxs.beginPath(); ctxs.arc(p.x,p.y,p.radius,0,Math.PI * 2); ctxs.fillStyle = 'rgba(255, 255, 255, 0.3)'; ctxs.fill(); }); for (let i = 0; i < particlesArr.length; i++) { for (let j = i + 1; j < particlesArr.length; j++) { const p1 = particlesArr[i]; const p2 = particlesArr[j]; const dx = p1.x - p2.x; const dy = p1.y - p2.y; const dist = Math.sqrt(dx * dx + dy * dy); if (dist < 100) { ctxs.strokeStyle = `rgba(255, 255, 255, ${(100 - dist) / 100 * 0.2})`; ctxs.lineWidth = 1; ctxs.beginPath(); ctxs.moveTo(p1.x,p1.y); ctxs.lineTo(p2.x,p2.y); ctxs.stroke(); } } } requestAnimationFrame(animateParticles); } animateParticles(); document.addEventListener('DOMContentLoaded',function() { const particlesContainer = document.getElementById('particles'); const tensDigit = document.getElementById('tens-digit'); const onesDigit = document.getElementById('ones-digit'); const treasureBox = document.getElementById('treasureBox'); const prize = document.getElementById('prize'); const prizeModal = document.getElementById('prizeModal'); const modalPrize = document.getElementById('modalPrize'); const countdown = document.getElementById('countdown'); const winnersList = document.getElementById('winnersList'); // 配置跳转链接 const redirectUrl = "https://www.baidu.com"; // 修改为您需要跳转的链接 // 奖品列表 const prizes = [ { type: "coupon",name: "💰 Cupom de R $30",value: "💰 Cupom de R $30" }, { type: "coupon",name: "💰 Cupom de R $50元",value: "💰 Cupom de R $50" }, { type: "coupon",name: "💰 Cupom de R $100",value: "💰 Cupom de R $100" }, { type: "coupon",name: "💰 Cupom de R $500",value: "💰 Cupom de R $500" }, { type: "coupon",name: "💰 Cupom de R 1000",value: "💰 Cupom de R $1000" }, { type: "discount",name: "🎟️ 20% OFF",value: "🎟️ 20% OFF" }, { type: "discount",name: "🎟️ 30% OFF",value: "🎟️ 30% OFF" }, { type: "discount",name: "🎟️ 40% OFF",value: "🎟️ 40% OFF" }, { type: "discount",name: "🎟️ 50% OFF",value: "🎟️ 50% OFF" }, { type: "discount",name: "🧰 Tesouro do amigo!",value: "🧰 Tesouro do amigo!" }, { type: "gift",name: "🎁 Surpresa especial!",value: "🎁 Surpresa especial!" } ]; let isOpened = false; let countdowns = 30; let countdownInterval; let isRunning = false; if (localStorage.getItem('downsTime') && localStorage.getItem('downsTime') > 0) { countdowns = localStorage.getItem('downsTime') document.querySelector(".countdown-container").style.display = 'flex' startCountdown() isOpened = true; isRunning = true; } else { document.querySelector(".countdown-container").style.display = 'none' countdowns = 30 } treasureBox.addEventListener('click',function() { if (isOpened) return; countdowns = 30 tensDigit.style.animation = ''; onesDigit.style.animation = ''; document.querySelector(".countdown-container").style.display = 'flex' isOpened = true; startCountdown() // 随机选择一个奖品 const randomPrize = prizes[Math.floor(Math.random() * prizes.length)]; document.querySelector('.treasure-base').classList.add('open') // 更新奖品显示 prize.textContent = randomPrize.value; prize.className = `prize ${randomPrize.type}`; // 显示奖品弹出动画 // 创建粒子效果 setTimeout(() => { prize.classList.add('show'); createConfetti(); setTimeout(() => { document.querySelector(".pointerImg").style.display = "block" },300) },800); // 显示弹窗 setTimeout(() => { modalPrize.textContent = randomPrize.name; prizeModal.style.display = 'flex'; // 开始倒计时 let seconds = 2; countdown.textContent = `Página redirecionará em ${seconds} segundos...`; const countdownInterval = setInterval(() => { seconds--; if (seconds > 0) { countdown.textContent = `Página redirecionará em ${seconds} segundos...`; } else { clearInterval(countdownInterval); prizeModal.style.display = 'none'; // 跳转到指定链接 // window.location.href = redirectUrl; } },1000); },1500); }); // 中奖名单数据 const winners = [ { name: "Lucas**",prize: "🎁",time: "recebeu um presente incrível há 1 minuto!" }, { name: "Mariana**",prize: "💸",time: "ganhou um bônus de 50 reais há 5 minutos!" }, { name: "Rafael**",prize: "📱",time: "ganhou um iPhone 14 há 10 minutos!" }, { name: "Camila**",prize: "🕹️",time: "recebeu itens de jogo incríveis há 23 minutos!" }, { name: "Gustavo**",prize: "🏆",time: "ganhou um prêmio de 1000 dólares há 38 minutos!" }, { name: "Gabriel**",prize: "💸",time: "ganhou um bônus de 100 reais há 44 minutos!" }, { name: "Marco**",prize: "🕹️",time: "recebeu itens de jogo incríveis há 56 minutos!" }, { name: "João**",prize: "🎁",time: "recebeu um presente incrível há 1 hora!" } ]; initWinnersList(); // 初始化中奖名单 function initWinnersList() { winnersList.innerHTML = ''; const container = document.createElement('div'); container.className = 'winner-items-container'; // 复制一份中奖名单,以实现更平滑的循环 const extendedWinners = [...winners,...winners]; extendedWinners.forEach(winner => { const winnerItem = document.createElement('div'); winnerItem.className = 'winner-item'; winnerItem.innerHTML = ` <div class="winner-prize">${winner.prize}</div> <div class="winner-name">${winner.name}</div> <div class="winner-time">${winner.time}</div> `; container.appendChild(winnerItem); }); winnersList.appendChild(container); } function createConfetti() { const colors = ['#ff0000','#00ff00','#0000ff','#ffff00','#ff00ff','#00ffff']; const container = document.querySelector('.treasure-container'); for (let i = 0; i < 100; i++) { const confetti = document.createElement('div'); confetti.className = 'confetti'; // 随机颜色 const color = colors[Math.floor(Math.random() * colors.length)]; confetti.style.backgroundColor = color; // 随机位置 const startX = Math.random() * 200 - 100 + treasureBox.offsetLeft + treasureBox.offsetWidth / 2; const startY = treasureBox.offsetTop + 200; confetti.style.left = startX + 'px'; confetti.style.top = startY + 'px'; container.appendChild(confetti); // 随机动画参数 const angle = Math.random() * Math.PI * 2; const velocity = 2 + Math.random() * 3; const rotation = Math.random() * 720 - 360; const size = 5 + Math.random() * 10; confetti.style.width = size + 'px'; confetti.style.height = size + 'px'; // 动画 const animation = confetti.animate([ { transform: `translate(0, 0) rotate(0deg)`, opacity: 1 }, { transform: `translate(${Math.cos(angle) * 100}px, -${150 + Math.random() * 200}px) rotate(${rotation}deg)`, opacity: 0 } ],{ duration: 1000 + Math.random() * 1000, easing: 'cubic-bezier(0.1, 0.8, 0.2, 1)' }); // 动画结束后移除元素 animation.onfinish = () => { confetti.remove(); }; } } // 创建粒子效果 function createParticles(x,y,count = 10) { for (let i = 0; i < count; i++) { const particle = document.createElement('div'); particle.classList.add('particle'); // 随机位置 const offsetX = (Math.random() - 0.5) * 100; const offsetY = (Math.random() - 0.5) * 100; particle.style.left = `${x + offsetX}px`; particle.style.top = `${y + offsetY}px`; // 随机动画参数 const size = Math.random() * 3 + 1; const duration = Math.random() * 1 + 0.5; const delay = Math.random() * 0.5; particle.style.width = `${size}px`; particle.style.height = `${size}px`; particle.style.animation = `particleFloat ${duration}s ease-out ${delay}s forwards`; // 添加到容器 particlesContainer.appendChild(particle); // 移除粒子 setTimeout(() => { particle.remove(); },(duration + delay) * 1000); } } // 添加粒子浮动动画 const styleSheet = document.styleSheets[0]; styleSheet.insertRule(` @keyframes particleFloat { 0% { transform: translate(0, 0); opacity: 1; } 100% { transform: translate(${Math.random() * 100 - 50}px, ${Math.random() * -100 - 50}px); opacity: 0; } } `,styleSheet.cssRules.length); // 更新数字显示 function updateDisplay() { const tens = Math.floor(countdowns / 10); const ones = countdowns % 10; // 添加翻转动画 if (tensDigit.textContent !== tens.toString()) { tensDigit.classList.remove('flip'); void tensDigit.offsetWidth; // 触发重排 tensDigit.classList.add('flip'); tensDigit.textContent = tens; // 在十位数变化时添加粒子效果 const rect = tensDigit.getBoundingClientRect(); createParticles(rect.left + rect.width / 2,rect.top + rect.height / 2,15); } if (onesDigit.textContent !== ones.toString()) { onesDigit.classList.remove('flip'); void onesDigit.offsetWidth; // 触发重排 onesDigit.classList.add('flip'); onesDigit.textContent = ones; // 在个位数变化时添加粒子效果 const rect = onesDigit.getBoundingClientRect(); createParticles(rect.left + rect.width / 2,rect.top + rect.height / 2,15); } } // 开始倒计时 function startCountdown() { if (isRunning) return; isRunning = true; countdownInterval = setInterval(() => { countdowns--; localStorage.setItem('downsTime',countdowns); updateDisplay(); isOpened = true; if (countdowns <= 1) { clearInterval(countdownInterval); isOpened = false; isRunning = false; // 倒计时结束效果 tensDigit.style.animation = 'pulse 0.5s infinite'; onesDigit.style.animation = 'pulse 0.5s infinite'; // 创建大量粒子 for (let i = 0; i < 50; i++) { setTimeout(() => { const rect1 = tensDigit.getBoundingClientRect(); const rect2 = onesDigit.getBoundingClientRect(); createParticles(rect1.left + rect1.width / 2,rect1.top + rect1.height / 2,5); createParticles(rect2.left + rect2.width / 2,rect2.top + rect2.height / 2,5); },i * 50); } setTimeout(() => { prize.classList.remove('show'); document.querySelector('.treasure-base').classList.remove('open') isOpened = false; isRunning = false; document.querySelector(".countdown-container").style.display = 'none' localStorage.setItem('downsTime',0); tensDigit.innerHTML = '3' onesDigit.innerHTML = '0' },1000) } },1000); } }); </script> </body> </html>当前代码如何优化
最新发布
10-24
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值