写一个js 滑动抽奖效果
这是一个简单的滑动抽奖效果的JS代码:
var lottery = document.getElementById('lottery');
var lotteryItems = lottery.getElementsByTagName('li');
var lotteryLength = lotteryItems.length;
var lotteryIndex = 0;
var lotteryTimer = null;
// 开始滑动
function startLottery() {
lotteryTimer = setInterval(function() {
// 取消上一个选中项的样式
lotteryItems[lotteryIndex].className = '';
// 计算下一个选中项的索引
lotteryIndex = (lotteryIndex + 1) % lotteryLength;
// 添加选中项的样式
lotteryItems[lotteryIndex].className = 'active';
}, 100);
}
// 停止滑动
function stopLottery() {
clearInterval(lotteryTimer);
}
// 绑定按钮事件
var startBtn = document.getElementById('startBtn');
var stopBtn = document.getElementById('stopBtn');
startBtn.onclick = startLottery;
stopBtn.onclick = stopLottery;
其中,lottery 是抽奖区域的 DOM 元素,lotteryItems 是抽奖项的 DOM 元素集合,lotteryLength 是抽奖项的数量,lotteryIndex 是当前选中项的索引,lotteryTimer 是滑动的定时器。startLottery 函数会每隔100毫秒计算出下一个选中项的索引,并将上一个选中项的样式清除,添加当前选中项的样式。stopLottery 函数用于停止滑动。最后,通过绑定按钮的点击事件来启动或停止滑动。
原文地址: https://www.cveoy.top/t/topic/ZyG 著作权归作者所有。请勿转载和采集!