2025.4.23 JavaScript 随机抽人网页学习笔记
一、项目概述
本项目旨在使用 JavaScript 创建一个简单实用的随机抽人网页,适用于课堂点名、活动抽奖等场景,通过轻松的操作实现从名单中随机抽取人员的功能。
二、功能需求
-
能够输入或多选人员名单。
-
点击按钮触发随机抽取过程,动态展示抽取效果。
-
显示抽取结果,并可进行重复抽取。
三、技术选型
主要使用 HTML 构建页面结构,CSS 进行页面样式设计,JavaScript 实现核心的随机抽取业务逻辑。
四、代码实现
HTML 部分
创建基本的页面结构,包含人员名单输入区、结果显示区以及操作按钮。
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>随机抽人</title><link rel="stylesheet" href="styles.css">
</head>
<body><div class="container"><h1>随机抽人</h1><div class="input-section"><h2>输入人员名单</h2><textarea id="peopleList" placeholder="请输入人员名单,每行一个"></textarea></div><button id="drawButton">开始抽取</button><div class="result-section"><h2>抽取结果</h2><div id="result"></div></div></div><script src="script.js"></script>
</body>
</html>
CSS 部分
对页面进行美化,使布局合理、视觉效果良好,突出显示重要元素如结果区域。
body {font-family: Arial, sans-serif;display: flex;justify-content: center;align-items: center;height: 100vh;margin: 0;background-color: #f5f5f5;
}.container {background-color: white;padding: 20px;border-radius: 10px;box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);width: 80%;max-width: 500px;
}h1 {text-align: center;color: #333;
}.input-section, .result-section {margin-bottom: 20px;
}textarea {width: 100%;height: 150px;padding: 10px;border: 1px solid #ccc;border-radius: 5px;resize: none;
}button {display: block;margin: 0 auto;padding: 10px 20px;background-color: #4CAF50;color: white;border: none;border-radius: 5px;cursor: pointer;font-size: 16px;
}button:hover {background-color: #45a049;
}#result {height: 50px;display: flex;justify-content: center;align-items: center;font-size: 24px;font-weight: bold;color: #333;background-color: #f9f9f9;border-radius: 5px;border: 1px solid #ddd;
}
JavaScript 部分
这是核心部分,处理人员名单的获取、随机抽取逻辑以及交互效果。
document.addEventListener('DOMContentLoaded', function() {const drawButton = document.getElementById('drawButton');const peopleListTextarea = document.getElementById('peopleList');const resultDiv = document.getElementById('result');drawButton.addEventListener('click', function() {// 获取名单并处理const peopleText = peopleListTextarea.value.trim();if (!peopleText) {alert('请输入人员名单!');return;}const peopleArray = peopleText.split('\n').filter(person => person.trim() !== '');if (peopleArray.length === 0) {alert('请输入有效的人员名单!');return;}// 随机抽取const randomIndex = Math.floor(Math.random() * peopleArray.length);const result = peopleArray[randomIndex];// 显示结果,可添加一些简单的动画效果resultDiv.textContent = result;// 简单动画效果:高亮显示resultDiv.style.backgroundColor = '#ffecb3';setTimeout(() => {resultDiv.style.backgroundColor = '#f9f9f9';}, 1000);});
});
五、功能测试与优化
-
功能测试 :在不同浏览器中打开网页,输入多种格式的人员名单进行抽取测试,确保抽取结果随机且正确显示。
-
优化方向 :可以增加人员名单的批量导入导出功能,优化抽取动画效果使其更加流畅自然,添加历史记录功能记录每次抽取结果等。
六、总结
通过这个项目,掌握了 JavaScript 基本的页面交互开发流程,从 HTML 结构搭建、CSS 样式美化到 JavaScript 逻辑实现,加深了对前端开发核心技术的理解和运用。同时,也认识到在实际开发中对用户体验细节的考虑,如输入验证、结果展示效果等,对于提升应用质量的重要性。