时间:2022-10-08 12:53:48 | 栏目:JavaScript代码 | 点击:次
一个用js编写的简单的抽奖系统,供大家参考,具体内容如下
效果图如图所示:字节带闪动,点击开始,可进行抽奖,并且按钮变为结束按钮,然后点击结束按钮,可以结束,并抽奖成功。
代码如下:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>抽奖</title> <style type="text/css"> table { width: 400px; height: 400px; border: gray solid 1px; border-collapse: collapse; text-align: center; margin: 0 auto; margin-top: 100px; } .td { border: gray solid 1px; background-color: lightskyblue; } .td1 { border: gray solid 1px; background-color: red; } td:hover { background-color: cornflowerblue; } div { width: 100px; height: 40px; margin-left: auto; margin-right: auto; margin-top: 20px; } #btn { width: 100px; height: 40px; } #blink{ width: 300px; height: 90px; margin-left: auto; margin-right: auto; margin-top: 20px; font-size: 70px; font: "微软雅黑"; text-align: center; font-weight: bold; } </style> </head> <body> <div id="blink"> 抽 奖 了 </div> <table> </table> <div> <input type="button" id="btn" value="开始" onclick="click1()" /> </div> </body> <script type="text/javascript"> /*利用二维数据+dom操作*/ var interval = 0; var table = document.querySelector("table"); var arr = [ [1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25] ] for(var i in arr) { var tr = table.insertRow(); for(var j in arr[i]) { var td = tr.insertCell(); td.setAttribute("class", "td"); td.innerHTML = arr[i][j]; } } //获取所有的td标签数组 var count = document.querySelectorAll("td"); function click1() { //找到当前按钮 var btn = document.querySelector("#btn"); //判断按钮状态 if(btn.value == '开始') { //点解后修改背景颜色 btn.style.backgroundColor = "red"; //修改按钮文字 btn.value = "结束"; //停止继续调用setInterval函数进行抽奖 clearInterval(interval); interval = setInterval(function() { var rad = Math.floor(Math.random() * 25); for(var i = 0; i < count.length; i++) { //通过遍历来重新给表设置样式 count[i].setAttribute("class", "td"); if(rad === i) { //给抽到的人改变样式 count[i].setAttribute('class', 'td1'); } } }, 100) } else { //设置背景颜色 btn.style.backgroundColor = "gainsboro"; //修改按钮文字 btn.value = "开始"; clearInterval(interval); } } function changeColor() { var color = "#f00|#0f0|#00f|#880|#808|#088|yellow|green|blue|gray"; color = color.split("|"); document.getElementById("blink").style.color = color[parseInt(Math.random() * color.length)]; } setInterval("changeColor()", 200); </script> </html>