js实现照片抽奖
实现照片抽奖功能
照片抽奖功能可以通过随机选择数组中的元素来实现,结合HTML和CSS展示抽奖效果。
HTML结构
创建一个简单的HTML结构,包含展示区域和按钮:
<div id="photo-container">
<img id="winner-photo" src="" alt="中奖照片">
</div>
<button id="draw-button">开始抽奖</button>
JavaScript代码
实现随机抽奖逻辑:
// 照片数组
const photos = [
{name: "照片1", url: "photo1.jpg"},
{name: "照片2", url: "photo2.jpg"},
// 添加更多照片
];
// 获取DOM元素
const photoElement = document.getElementById('winner-photo');
const drawButton = document.getElementById('draw-button');
// 抽奖函数
function drawWinner() {
// 禁用按钮防止重复点击
drawButton.disabled = true;
// 动画效果
let counter = 0;
const interval = setInterval(() => {
const randomIndex = Math.floor(Math.random() * photos.length);
photoElement.src = photos[randomIndex].url;
photoElement.alt = photos[randomIndex].name;
counter++;
if(counter > 20) {
clearInterval(interval);
drawButton.disabled = false;
}
}, 100);
}
// 绑定事件
drawButton.addEventListener('click', drawWinner);
CSS样式
添加基本样式增强视觉效果:
#photo-container {
width: 300px;
height: 300px;
border: 2px solid #ccc;
margin: 20px auto;
display: flex;
align-items: center;
justify-content: center;
}
#winner-photo {
max-width: 100%;
max-height: 100%;
}
#draw-button {
display: block;
margin: 0 auto;
padding: 10px 20px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 16px;
}
高级功能扩展
-
添加音效增强体验:
// 在drawWinner函数中添加 const audio = new Audio('drumroll.mp3'); audio.play(); // 在clearInterval后添加 audio.pause(); audio.currentTime = 0; -
获奖名单记录:
const winners = []; // 在drawWinner函数最后添加 winners.push(photos[randomIndex]); console.log('获奖名单:', winners); -
排除已中奖照片:
// 修改照片数组为未中奖照片 const availablePhotos = photos.filter(photo => !winners.includes(photo)); // 使用availablePhotos代替photos进行抽奖
注意事项
- 确保照片路径正确
- 对于大量照片考虑懒加载
- 移动端需要调整样式
- 可添加过渡动画增强视觉效果
这种方法创建的照片抽奖系统简单易用,可根据需求进一步扩展功能。







