抽奖活动JS设计的思路是当主持人点击开始,系统每次随机显示候选者名称,并随机一个时间停止,最后一次显示的候选者名称即为本轮抽奖活动的获胜者!

活动页面的HTML代码

<h1 style="color:gold; text-align:center;margin-bottom:50px; font-size:28px;">@Model.Name</h1>
<h1 style="color:gold; text-align:center;" id="winner">幸运星</h1>
<h1 style="color:gold; text-align:center; margin-top:80px;">
    <span id="shangbig" class="shangbig" style="text-align:center;display:inline-block;" onclick="start()">
        开始抽奖
    </span>
</h1>
<p style="color:gold; text-align:center;margin-bottom:30px;">
    本奖项已有
    <span style="color:red;font-size:18px;font-weight:bold;" id="total"></span> 位幸运星获取,还剩
    <span style="color:red;font-size:18px;font-weight:bold;" id="remain"></span> 个名额
</p>
<p style="color:gold; text-align:center;margin-bottom:30px;">
    参与人员:<span id="usernames"></span>
</p>
JS代码的实现
<script>
    users = [];
    ReserveNum = @Model.ReserveNum;
    var gameStart = false;
    start = function () {
        if (gameStart == true || users.length < 1 || ReserveNum<1) return;
        gameStart = true;
        var times = randomNum(6000, 10000);
        var remainTime = times;
        $("#shangbig").addClass("shangbig_on");
          var gameInterval=  setInterval(function () {
              $("#winner").html(users[Math.floor(Math.random() * users.length)]);
              remainTime = remainTime - 50;
              $("#shangbig").html("请等待...");
              if (remainTime < 0) {
                  clearInterval(gameInterval);
                  gameStart = false;
                  $("#shangbig").removeClass("shangbig_on").html("开始");
                  var winnerAccount = $("#winner").html();
                  $("#winner").html(winnerAccount);
                  $.getJSON("/a/RedPackWin?account=" + winnerAccount + "&articleInfoId=@Model.Id", function (data) {
                      ReserveNum = data.ReserveNum;
                      UpdateWinnerCount();
                      UpdateRedPackReserveNum();
                      UpdateRedPackUsers();
                  });
              }
          }, 50);
    };

    UpdateWinnerCount = function () {
        $.getJSON("/a/RedPackWinerCount/@Model.Id", function (data) {
            $("#total").html(data.WinerCount);
        });
    }
    UpdateRedPackReserveNum = function () {
            $.getJSON("/a/RedPackReserveNum/@Model.Id", function (data) {
                $("#remain").html(data.ReserveNum);
        });
    }
    UpdateRedPackUsers = function () {
        $.getJSON("/a/RedPackUsers", function (data) {
            if (data.UsersNames === "") users = [];
            else users = data.UsersNames.split(",");
            $("#usernames").html(data.UsersNames);
        });
    }
    UpdateWinnerCount();
    UpdateRedPackReserveNum();
    UpdateRedPackUsers();
</script>
JS抽奖活动的代码也使用了Ajax调用后端接口,将获奖用户存入数据库待以后查询使用也防止同一用户被多次抽中,对JS抽奖感兴趣或有疑问的同学可以留言询问哦!