用JavaScript+HTML实现双色球随机摇号效果
首先要知道双色球的规则是什么
双色球投注区分为红球号码区和蓝球号码区
红球号码范围为01~33,蓝球号码范围为01~16
双色球每期从33个红球中开出6个号码,从16个蓝球中开出1个号码作为中奖号码
双色球玩法即是竞猜开奖号码的6个红球号码和1个蓝球号码,顺序不限
知道了规则以后,我们就可以用代码实现了,废话不到说,直接上代码:
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>双色球</title><style>span {/*display: none;*/margin: 5px;font-size: 30px;width: 70px;height: 70px;background-color: red;color: white;text-align: center;line-height: 70px;display: inline-block;border-radius: 50%;}.blue {background-color: blue;}button {width: 75px;height: 40px;font-size: 20px;border: none;color: white;background-color: gray;cursor: pointer;}</style>
</head>
<body>
<p><span class="red"></span><span class="red"></span><span class="red"></span><span class="red"></span><span class="red"></span><span class="red"></span><span class="blue"></span>
</p>
<button>摇号</button>
</body>
</html>
<script>// 红色球号码从1--33中选择;蓝色球号码从1--16中选择let spanRed = document.querySelectorAll('.red');let spanBlue = document.querySelector('.blue');let btn = document.querySelector('button')/*** 返回一个指定数值范围(start~end)内的、元素互不重复的、且长度为len随机数组* @param start* @param end* @param len* @returns {any[]}*/function maker(start, end, len) {let set = new Set(new Array(len));set.clear();for (; ;) {let ok = Math.round(Math.random() * (end - start)) + start;if (!set.has(ok)) {set.add(ok);}if (set.size === len) {break;}}//集合转化为数组return Array.from(set);}function randomNumber() {let red = maker(1, 33, spanRed.length);for (let i = 0; i < spanRed.length; i++) {spanRed[i].innerHTML = red[i];}let blue = maker(1, 16, 1);spanBlue.innerHTML = blue[0];}randomNumber();btn.addEventListener('click', randomNumber);</script>
运行后如下:
点击摇号,产生一组随机数