写一个纯前端的抽奖程序
- User
写一个纯前端的抽奖程序
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
写一个纯前端的抽奖程序
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
好的,这是一个功能完整、界面美观的纯前端抽奖程序。它使用 HTML、CSS 和 JavaScript 实现,无需任何后端支持。
这个抽奖程序采用了经典的九宫格布局,点击中间的按钮开始,高亮框会快速闪动,最终停在一个奖品上。
你可以将下面的代码复制到一个 index.html 文件中,然后用浏览器打开即可运行。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>九宫格抽奖</title>
<style>
:root {
--primary-color: #ff5722;
--secondary-color: #ff9800;
--bg-color: #fcece3;
--text-color: #333;
--border-color: #ffc9a8;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
margin: 0;
background: linear-gradient(135deg, #fdfcfb 0%, #e2d1c3 100%);
}
.container {
background: white;
padding: 30px;
border-radius: 20px;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
text-align: center;
max-width: 500px;
width: 90%;
}
h1 {
color: var(--primary-color);
margin-bottom: 25px;
font-size: 2em;
}
.lottery-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: repeat(3, 1fr);
gap: 15px;
margin-bottom: 30px;
}
.grid-item {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
background-color: var(--bg-color);
border: 2px solid var(--border-color);
border-radius: 10px;
aspect-ratio: 1 / 1;
transition: all 0.2s ease-in-out;
cursor: default;
}
.item-icon {
font-size: 2em;
margin-bottom: 5px;
}
.item-name {
font-size: 0.9em;
color: var(--text-color);
font-weight: 500;
}
.grid-item.active {
background-color: var(--primary-color);
border-color: var(--secondary-color);
transform: scale(1.08);
box-shadow: 0 0 20px rgba(255, 87, 34, 0.5);
}
.grid-item.active .item-name {
color: white;
font-weight: bold;
}
#start-btn {
background: linear-gradient(45deg, var(--primary-color), var(--secondary-color));
color: white;
font-size: 1.5em;
font-weight: bold;
cursor: pointer;
border: none;
user-select: none;
}
#start-btn:hover {
opacity: 0.9;
}
#start-btn:disabled {
background: #ccc;
cursor: not-allowed;
}
.result-panel {
margin-top: 20px;
}
#result-display {
font-size: 1.2em;
font-weight: bold;
color: var(--primary-color);
min-height: 30px;
transition: opacity 0.3s;
}
.history-list {
margin-top: 20px;
max-height: 150px;
overflow-y: auto;
background-color: #fafafa;
border-radius: 8px;
padding: 10px;
text-align: left;
}
.history-list h3 {
margin-top: 0;
margin-bottom: 10px;
color: #555;
border-bottom: 1px solid #eee;
padding-bottom: 5px;
}
.history-list ul {
list-style: none;
padding: 0;
margin: 0;
}
.history-list li {
padding: 5px 0;
color: #666;
border-bottom: 1px dashed #ddd;
}
.history-list li:last-child {
border-bottom: none;
}
</style>
</head>
<body>
<div class="container">
<h1>幸运大抽奖</h1>
<div class="lottery-grid" id="lottery-grid">
<!-- 奖品格子将由 JS 动态生成 -->
</div>
<div class="result-panel">
<p id="result-display"></p>
</div>
<div class="history-list" id="history-list" style="display: none;">
<h3>中奖记录</h3>
<ul id="history-ul"></ul>
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', () => {
// --- 1. 配置区域 ---
const prizes = [
{ id: 1, name: '一等奖', icon: '🏆' },
{ id: 2, name: '二等奖', icon: '🥈' },
{ id: 3, name: '三等奖', icon: '🥉' },
{ id: 4, name: '谢谢参与', icon: '😅' },
{ id: 5, name: '优惠券', icon: '🎟️' },
{ id: 6, name: '小礼品', icon: '🎁' },
{ id: 7, name: '积分+50', icon: '✨' },
{ id: 8, name: '再来一次', icon: '🔁' }
];
// 抽奖动画相关的配置
const config = {
totalDuration: 4000, // 总抽奖时长 (毫秒)
accelerationTime: 1200, // 加速阶段时长
decelerationTime: 1500, // 减速阶段时长
minSpeed: 250, // 最慢速度 (毫秒/格)
maxSpeed: 60, // 最快速度 (毫秒/格)
};
// --- 2. DOM 元素获取 ---
const grid = document.getElementById('lottery-grid');
const resultDisplay = document.getElementById('result-display');
const historyListContainer = document.getElementById('history-list');
const historyUl = document.getElementById('history-ul');
let startBtn; // 开始按钮在初始化时创建
// --- 3. 状态变量 ---
let isDrawing = false;
let gridItems = [];
// 定义九宫格的闪动顺序,从左上角顺时针
const drawOrder = [0, 1, 2, 5, 8, 7, 6, 3];
// --- 4. 初始化函数 ---
function initializeGrid() {
grid.innerHTML = '';
const prizeItems = [...prizes];
for (let i = 0; i < 9; i++) {
const item = document.createElement('div');
item.classList.add('grid-item');
if (i === 4) { // 中心位置是开始按钮
item.id = 'start-btn';
item.textContent = '开始抽奖';
startBtn = item;
} else {
// 从奖品数组中取一个,为了避免重复,可以从数组中移除
const prize = prizeItems.shift();
item.innerHTML = `
<div class="item-icon">${prize.icon}</div>
<div class="item-name">${prize.name}</div>
`;
item.dataset.prizeId = prize.id;
}
grid.appendChild(item);
}
gridItems = Array.from(grid.querySelectorAll('.grid-item:not(#start-btn)'));
// 绑定事件
startBtn.addEventListener('click', startDraw);
}
// --- 5. 核心抽奖逻辑 ---
function startDraw() {
if (isDrawing) return;
isDrawing = true;
startBtn.disabled = true;
resultDisplay.textContent = '抽奖中,祝您好运...';
// 模拟后端请求,决定中奖结果
// 在纯前端中,我们直接随机一个奖品
const winningPrizeIndex = Math.floor(Math.random() * prizes.length);
const winningPrize = prizes[winningPrizeIndex];
// 在 drawOrder 中找到中奖奖品对应的位置
const finalPosition = drawOrder.findIndex(pos => {
const item = grid.children[pos];
return parseInt(item.dataset.prizeId) === winningPrize.id;
});
runAnimation(finalPosition, winningPrize);
}
function runAnimation(finalPosition, winningPrize) {
let currentIndex = 0;
let currentSpeed = config.maxSpeed;
let timer;
const startTime = Date.now();
function animate() {
const elapsedTime = Date.now() - startTime;
// 移除上一个高亮
const lastActivePosition = drawOrder[currentIndex % drawOrder.length];
grid.children[lastActivePosition].classList.remove('active');
// 更新索引
currentIndex++;
// 添加新高亮
const currentActivePosition = drawOrder[currentIndex % drawOrder.length];
grid.children[currentActivePosition].classList.add('active');
// --- 速度控制 ---
if (elapsedTime < config.accelerationTime) {
// 加速阶段
currentSpeed = config.maxSpeed + (config.minSpeed - config.maxSpeed) * (elapsedTime / config.accelerationTime);
} else if (elapsedTime > config.totalDuration - config.decelerationTime) {
// 减速阶段
const decelerationProgress = (elapsedTime - (config.totalDuration - config.decelerationTime)) / config.decelerationTime;
currentSpeed = config.maxSpeed + (config.minSpeed - config.maxSpeed) * (1 - decelerationProgress * decelerationProgress);
} else {
// 匀速阶段
currentSpeed = config.maxSpeed;
}
// 检查是否结束
if (elapsedTime >= config.totalDuration) {
// 确保最终停在正确位置
const finalItemPosition = drawOrder[finalPosition];
Array.from(grid.children).forEach(child => child.classList.remove('active'));
grid.children[finalItemPosition].classList.add('active');
// 显示结果
showResult(winningPrize);
return;
}
timer = setTimeout(animate, currentSpeed);
}
animate();
}
// --- 6. 结果与历史记录 ---
function showResult(prize) {
resultDisplay.textContent = `恭喜你,抽中了:${prize.name}!`;
isDrawing = false;
startBtn.disabled = false;
// 添加到历史记录
addHistory(prize);
}
function addHistory(prize) {
historyListContainer.style.display = 'block';
const li = document.createElement('li');
li.textContent = `[${new Date().toLocaleTimeString()}] 抽中 ${prize.icon} ${prize.name}`;
historyUl.prepend(li); // 新记录放在最上面
}
// --- 7. 启动程序 ---
initializeGrid();
});
</script>
</body>
</html>
可配置性强:
prizes 数组中轻松修改奖品名称、图标和数量。目前是8个奖品,正好填满九宫格的周围。config 对象允许你调整抽奖动画的总时长、速度曲线等,让动画效果更符合你的需求。现代化的视觉效果:
纯前端实现:
Math.random() 随机确定的,动画只是为了视觉效果。这是最常见的实现方式。中奖记录:
prizes 数组。可以增加、删除或修改其中的对象。确保奖品数量为8个以适配九宫格。<style> 标签内,修改 :root 中的 CSS 变量可以快速改变整体配色。例如,将 --primary-color 改成你喜欢的颜色。config 对象中的数值。
totalDuration:总时长,越长转得越久。minSpeed 和 maxSpeed:控制动画的最慢和最快速度。这个抽奖程序是一个很好的起点,你可以基于它进行扩展,比如:
fetch API 从服务器获取,确保抽奖的公平性和可控性。localStorage 记录用户的抽奖次数。