• js制作九宫格抽奖功能


    HTML代码:

    1. <div id="lottery">
    2. <div class="lottery-item">1</div>
    3. <div class="lottery-item">2</div>
    4. <div class="lottery-item">3</div>
    5. <div class="lottery-item">4</div>
    6. <div class="lottery-item">5</div>
    7. <div class="lottery-item">6</div>
    8. <div class="lottery-item">7</div>
    9. <div class="lottery-item">8</div>
    10. <div class="lottery-item">9</div>
    11. </div>
    12. <button id="start-btn">开始抽奖</button>

    CSS代码:

    1. #lottery {
    2. display: flex;
    3. flex-wrap: wrap;
    4. width: 300px;
    5. height: 300px;
    6. margin: 0 auto;
    7. background-color: #e6e6e6;
    8. }
    9. .lottery-item {
    10. width: 100px;
    11. height: 100px;
    12. font-size: 50px;
    13. text-align: center;
    14. line-height: 100px;
    15. background-color: #fff;
    16. border: 1px solid #ccc;
    17. }
    18. .lottery-active {
    19. background-color: orange;
    20. }

    JavaScript代码:

    1. var items = document.getElementsByClassName('lottery-item');
    2. var btn = document.getElementById('start-btn');
    3. var index = 0;
    4. var timer = null;
    5. btn.onclick = function() {
    6. if(timer) {
    7. clearInterval(timer);
    8. timer = null;
    9. // 停止时将当前选中项背景色还原
    10. items[index].classList.remove('lottery-active');
    11. } else {
    12. timer = setInterval(function() {
    13. // 先将当前选中项背景色还原
    14. items[index].classList.remove('lottery-active');
    15. index ++;
    16. if(index > 8) {
    17. index = 0;
    18. }
    19. // 设置当前选中项的背景色
    20. items[index].classList.add('lottery-active');
    21. }, 100);
    22. }
    23. }

    通过点击按钮,可以开始或停止抽奖的功能。其中,抽奖的动画效果是通过定时器实现的,每隔一段时间改变当前选中项的背景色来模拟抽奖的过程。当停止抽奖时,定时器会被清除,当前选中项的背景色会还原。

  • 相关阅读:
    混合与剔除
    android Framework 中用到了哪些跨进程通信方式?
    Ajax技术
    什么是微格式
    Vite3 + Svelte3使用@import导入scss样式
    北美”闲鱼”Poshmark,如何销售提高成单率?附防封养号攻略
    minikube搭建k8s
    入股合作协议要不要写章程
    目前世界上有多少种编程语言
    Packet Sniffing and Spoofing Lab(报文嗅探&欺骗SEED 实验)
  • 原文地址:https://blog.csdn.net/m0_74265396/article/details/134484960