
前言
无论是在手机 App 端,还是网页,在活动日的时候,商家都会弄些抽奖的活动,抽金币,金劵等。
纯 js 如何实现一个轻量级的抽奖程序呢?
废话不多说,直接上代码。
Vue 实现
实现原理也很简单:
-
定义一个候选人数组 lists;
-
通过 Math.random() 生成随机数;
-
将生成的随机数乘以数组的最大下标值,并向下取整,获取数组的随机下标值。
-
通过定时器实现重复循环生成候选人数组随机下标值,直到点击停止,获取中奖人对应的数组下标值。
<template></template> <script> export default { data() { return { lists: ['张三','李四','王五','小刘','罗胖','胡玲','周通','徐达','杨新'], timer: null, // 定时器 result: '', randIndex: null } },抽奖名单
- {{item}}
<el-button type="primary" @click="handleStart">开始抽奖</el-button> <el-button type="success" @click="handleStop">停止抽奖</el-button> 抽奖结果:{{this.result}}methods: { // 开始抽奖 handleStart() { if(!this.timer) { // 创建定时器 this.timer = setInterval(() => { let max = this.lists.length-1; // 最大的下标数字 let rand = Math.random(); // 随机数,小于0 // 定义一个random()函数,原理是 随机数和最大值减最小值的差相乘 最后再加上最小值 // Math.floor(Math.random() * (max - min)) + min this.randIndex = Math.floor(rand*max)+1; // 向下取整 this.result = this.lists[this.randIndex] // 得到的结果 },50) } }, // 停止抽奖 handleStop() { clearInterval(this.timer); // 清除定时器 this.timer = null; this.result = this.lists[this.randIndex]; this.$message({ message: `中奖的是${this.result}`, type: 'success' }); } }}
<style lang="scss" scoped> .choujiang-wrap { text-align: center; margin-top: 10px; }
</script></style>.choujiang-item { display:flex; justify-content: center; } .choujiang-item li { margin-right: 10px; } .active { color: red; font-weight: bold; } .btn { margin-top: 20px; }
通过上面的代码,我们就能实现一个简易的抽奖程序。
🎁 福利时间
如果你正在备战面试或者想要学习其他知识,给大家推荐一个宝藏知识库,作者整理了一些列 Java 程序员需要掌握的核心知识,有需要的自取不谢。
知识库地址:https://farerboy.com/
