通过HTML和JavaScript实现随机抽取幸运员工

发布时间 2023-09-28 22:39:29作者: qwerrt9

需求描述: 公司经常会要求IT部门做一个小功能给公司随机抽取员工

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>员工分享工作感悟</title>
    <style>
        body {
            margin: 0;
            padding: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            background: linear-gradient(to right, #f06, #9f6);
            font-family: Arial, sans-serif;
        }
        .container {
            text-align: center;
            color: #fff;
        }
        h1 {
            font-size: 70px;
            margin-bottom: 20px;
        }
        p {
            font-size: 80px;
            margin-bottom: 100px;
            line-height: 2; /* 调整行间距 */
        }
        .highlighted {
            font-size: 120px;
            font-weight: bold;
            color: #FFD700; /* 黄色 */
        }
        button {
            background-color: #007BFF;
            color: #fff;
            border: none;
            padding: 10px 20px;
            font-size: 50px;
            border-radius: 5px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }
        button:hover {
            background-color: #0056b3;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>2023年度公司幸运员工</h1>
        <p>今天的幸运员工是:<span id="selectedEmployee" class="highlighted">员工1</span></p>
        <button onclick="startRandomSelection()">开始随机选择</button>
        <button onclick="stopRandomSelection()">停止选择</button>
    </div>

    <script>
        var employee_list = [
            "员工1", "员工2", "员工3", "员工4", "员工5", 
            // ...
            "员工96", "员工97", "员工98", "员工99", "员工100"
        ];

        var intervalId;
        var isRandomSelecting = false;

        // 随机选择员工
        function selectEmployeeRandomly() {
            var selectedEmployee = employee_list[Math.floor(Math.random() * employee_list.length)];
            document.getElementById("selectedEmployee").textContent = selectedEmployee;
        }

        // 开始随机选择
        function startRandomSelection() {
            if (!isRandomSelecting) {
                intervalId = setInterval(selectEmployeeRandomly, 100);
                isRandomSelecting = true;
            }
        }

        // 停止选择
        function stopRandomSelection() {
            clearInterval(intervalId);
            isRandomSelecting = false;
        }

        // 页面加载后自动开始随机选择
        window.onload = function() {
            startRandomSelection();
        }
    </script>
</body>
</html>

对应效果图如下所示