Web第三次作业

发布于:2025-08-14 ⋅ 阅读:(24) ⋅ 点赞:(0)

一、使用js完成抽奖项目效果和内容自定义

代码如下:

<!DOCTYPE html>
<html>
<head>
    <title>抽奖</title>
    <style>
        body { font-family: Arial; text-align: center; margin-top: 50px; }
        #prizes { display: flex; justify-content: center; margin: 30px; }
        .prize { padding: 15px; margin: 10px; border: 1px solid #ddd; min-width: 100px; }
        .active { background: #ffeb3b; font-weight: bold; }
        button { padding: 10px 20px; font-size: 16px; cursor: pointer; }
        #result { margin: 20px; font-size: 24px; min-height: 40px; }
    </style>
</head>
<body>
    <h1>幸运抽奖</h1>
    <div id="prizes"></div>
    <button id="start">开始</button>
    <button id="stop" disabled>停止</button>
    <div id="result"></div>

    <script>
        const prizes = ["一等奖", "二等奖", "三等奖", "谢谢参与", "再来一次"];
        let current = 0, timer, isRolling = false;
        
        function renderPrizes() {
            document.getElementById('prizes').innerHTML = prizes
                .map((p, i) => `<div class="prize" data-idx="${i}">${p}</div>`).join('');
        }
        
        document.getElementById('start').addEventListener('click', () => {
            if(isRolling) return;
            isRolling = true;
            document.getElementById('start').disabled = true;
            document.getElementById('stop').disabled = false;
            document.getElementById('result').innerHTML = '';
            
            timer = setInterval(() => {
                document.querySelector('.active')?.classList.remove('active');
                current = (current + 1) % prizes.length;
                document.querySelector(`[data-idx="${current}"]`).classList.add('active');
            }, 200);
        });
        
        document.getElementById('stop').addEventListener('click', () => {
            clearInterval(timer);
            isRolling = false;
            document.getElementById('start').disabled = false;
            document.getElementById('stop').disabled = true;
            document.getElementById('result').innerHTML = `恭喜获得: ${prizes[current]}`;
        });
        
        renderPrizes();
    </script>
</body>
</html>

运行结果如图: