jquery 抽奖
jQuery 抽奖实现方法
基础抽奖功能实现
使用 jQuery 实现一个简单的抽奖功能可以通过随机选择数组中的元素来完成。以下是一个基础示例:
$(document).ready(function() {
var prizes = ["一等奖", "二等奖", "三等奖", "谢谢参与"];
var isRolling = false;
$("#start-btn").click(function() {
if(isRolling) return;
isRolling = true;
var rollInterval = setInterval(function() {
var randomIndex = Math.floor(Math.random() * prizes.length);
$("#result").text(prizes[randomIndex]);
}, 100);
setTimeout(function() {
clearInterval(rollInterval);
var finalIndex = Math.floor(Math.random() * prizes.length);
$("#result").text(prizes[finalIndex]);
isRolling = false;
}, 2000);
});
});
带权重的高级抽奖
如果需要设置不同奖项的中奖概率,可以使用权重系统:
var prizePool = [
{name: "特等奖", weight: 1},
{name: "一等奖", weight: 5},
{name: "二等奖", weight: 10},
{name: "三等奖", weight: 20},
{name: "谢谢参与", weight: 64}
];
function getRandomPrize() {
var totalWeight = prizePool.reduce((sum, prize) => sum + prize.weight, 0);
var random = Math.random() * totalWeight;
var weightSum = 0;
for(var i = 0; i < prizePool.length; i++) {
weightSum += prizePool[i].weight;
if(random <= weightSum) {
return prizePool[i];
}
}
}
视觉动画效果增强
为抽奖过程添加更丰富的动画效果:
$("#start-btn").click(function() {
var $prizeItems = $(".prize-item");
var currentActive = 0;
var rollSpeed = 100;
var roll = setInterval(function() {
$prizeItems.removeClass("active");
$prizeItems.eq(currentActive).addClass("active");
currentActive = (currentActive + 1) % $prizeItems.length;
}, rollSpeed);
setTimeout(function() {
clearInterval(roll);
rollSpeed += 20;
var slowRoll = setInterval(function() {
$prizeItems.removeClass("active");
$prizeItems.eq(currentActive).addClass("active");
currentActive = (currentActive + 1) % $prizeItems.length;
rollSpeed += 50;
if(rollSpeed > 500) {
clearInterval(slowRoll);
var finalPrize = getRandomPrize();
showResult(finalPrize);
}
}, rollSpeed);
}, 2000);
});
转盘式抽奖实现
对于转盘形式的抽奖界面:
function startRoulette() {
var $wheel = $(".wheel");
var rotation = 0;
var spinDuration = 3000;
var prizeAngle = 360 / prizePool.length;
var targetPrize = getRandomPrize();
var targetIndex = prizePool.findIndex(p => p.name === targetPrize.name);
var targetRotation = 360 * 5 + (360 - (targetIndex * prizeAngle));
$wheel.css({
'transition': `transform ${spinDuration}ms cubic-bezier(0.17, 0.85, 0.43, 1)`,
'transform': `rotate(${targetRotation}deg)`
});
setTimeout(function() {
alert("恭喜获得:" + targetPrize.name);
$wheel.css({
'transition': 'none',
'transform': `rotate(${targetRotation % 360}deg)`
});
}, spinDuration);
}
服务器端验证
为确保抽奖公平性,可以与服务器端配合:
$("#start-btn").click(function() {
$.ajax({
url: "/api/draw",
type: "POST",
success: function(response) {
if(response.success) {
animatePrize(response.prize);
} else {
alert(response.message);
}
}
});
});
这些方法提供了从简单到复杂的 jQuery 抽奖实现方案,可根据实际需求选择合适的方案或组合使用。







