当前位置: 首页 > news >正文

Web前端:JavaScript 随机点名系统案例详解

案例概述

这个HTML页面实现了一个随机点名系统,包含以下功能:

  1. 点击按钮随机选择一名学生

  2. 每次点击随机改变背景颜色

  3. 同时改变显示的学生姓名颜色

  4. 显示区域全屏居中显示

核心实现原理

1. 页面结构与样式
<body><div class="box">******</div><button class="btn">改变颜色</button><!-- JavaScript代码 -->
</body>
  • box元素

    • 占据整个视口(100%宽,100vh高)

    • 文本居中(text-align: center)

    • 行高等于高度(line-height: 100vh)实现完美垂直居中

    • 大号字体(font-size: 100px)

  • 按钮元素

    • 绝对定位(position: absolute)

    • 位于页面底部30%位置(bottom: 30%)

    • 水平居中(left: calc(50% - 100px))

 2. JavaScript核心逻辑
学生数据存储
var names = ["⽢⼤鹏", "廖亿城", "邓新宇", "徐正洋", "丁俊豪", "蒋⾦平", "李健", "廖伟鑫", "施雅典", "沈江余", "付锦铭", "罗志强", "董杨兴", "李伟"
];

使用数组存储学生姓名,便于随机访问。

随机数生成函数
function GetRandom(min, max) {return Math.floor(Math.random() * (max - min + 1) + min);
}

这个函数的作用是生成指定范围内的随机整数:

  1. Math.random() 生成[0,1)的随机小数

  2. 乘以范围长度 (max - min + 1) 得到[0, max-min+1)的随机浮点数

  3. 加上最小值min得到[min, max+1)的随机浮点数

  4. Math.floor() 向下取整,得到[min, max]的整数

按钮点击事件处理
btn.onclick = () => {// 生成随机RGBA颜色值var r = Math.floor(Math.random() * 255);var g = Math.floor(Math.random() * 255);var b = Math.floor(Math.random() * 255);var a = Math.random();// 随机选择学生var Random = GetRandom(0, names.length - 1);// 应用样式box.style.backgroundColor = `rgba(${r},${g},${b},${a})`;box.innerHTML = `${names[Random]}`;box.style.color = `rgb(${g},${r},${b})`;
}

关键知识点详解

1. Math.random()的应用

  • 背景颜色RGB分量:Math.random() * 255 → [0, 255)的浮点数 → Math.floor()取整

  • 透明度alpha:Math.random() → [0, 1)的浮点数

  • 学生索引:GetRandom(0, names.length-1) 确保不越界

2. RGBA颜色模型

  • RGB: 红、绿、蓝分量(0-255整数)

  • A: Alpha透明度(0-1浮点数)

  • CSS表示:rgba(255, 100, 50, 0.8)

3. 文本颜色设计技巧 

box.style.color = `rgb(${g},${r},${b})`;

这里使用RGB分量重新排列(g,r,b)生成文本颜色,确保:

  1. 文本颜色与背景颜色不同

  2. 但又有一定的关联性

  3. 避免完全随机的颜色组合导致对比度不足

4. 界面布局技巧

  • 垂直居中文本line-height = height 是最简单的单行文本垂直居中方案

  • 按钮居中left: calc(50% - 100px) 通过计算实现水平居中

  • 全屏背景width: 100%; height: 100vh; 确保覆盖整个视口

完整代码 

<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>随机点名系统</title><style>* {margin: 0;padding: 0;box-sizing: border-box;font-family: 'Microsoft YaHei', sans-serif;}body {overflow: hidden;background: linear-gradient(135deg, #1a2a6c, #b21f1f, #1a2a6c);}.container {display: flex;flex-direction: column;justify-content: center;align-items: center;min-height: 100vh;padding: 20px;}.title {color: white;text-align: center;margin-bottom: 30px;text-shadow: 0 2px 10px rgba(0,0,0,0.5);}.title h1 {font-size: 2.8rem;margin-bottom: 10px;}.title p {font-size: 1.2rem;opacity: 0.8;}.box {width: 90%;max-width: 800px;height: 60vh;background-color: rgba(0, 0, 0, 0.7);border-radius: 20px;display: flex;justify-content: center;align-items: center;font-size: 4rem;color: white;text-align: center;padding: 20px;box-shadow: 0 10px 30px rgba(0,0,0,0.5);transition: all 0.5s ease;margin-bottom: 30px;border: 3px solid rgba(255,255,255,0.1);overflow: hidden;position: relative;}.btn {width: 220px;height: 80px;background: linear-gradient(45deg, #ff416c, #ff4b2b);color: white;font-size: 1.5rem;font-weight: bold;border: none;border-radius: 50px;cursor: pointer;box-shadow: 0 5px 15px rgba(0,0,0,0.3);transition: all 0.3s ease;outline: none;margin-top: 20px;}.btn:hover {transform: translateY(-5px);box-shadow: 0 8px 20px rgba(0,0,0,0.4);background: linear-gradient(45deg, #ff4b2b, #ff416c);}.btn:active {transform: translateY(0);}.info-panel {background: rgba(255,255,255,0.1);border-radius: 10px;padding: 15px 25px;color: white;font-size: 1.1rem;margin-top: 20px;text-align: center;backdrop-filter: blur(5px);}.student-count {font-weight: bold;color: #ffcc00;font-size: 1.2rem;}@media (max-width: 768px) {.box {font-size: 3rem;height: 50vh;}.title h1 {font-size: 2rem;}}</style>
</head><body><div class="container"><div class="title"><h1>随机点名系统</h1><p>点击按钮随机选择学生并改变背景颜色</p></div><div class="box" id="displayBox">******</div><button class="btn" id="actionBtn">随机点名</button><div class="info-panel">学生库中共有 <span class="student-count" id="countEl">14</span> 名学生</div></div><script>// 获取DOM元素const box = document.getElementById('displayBox');const btn = document.getElementById('actionBtn');const countEl = document.getElementById('countEl');// 学生名单const names = ["⽢⼤鹏", "廖亿城", "邓新宇", "徐正洋", "丁俊豪", "蒋⾦平", "李健", "廖伟鑫", "施雅典", "沈江余", "付锦铭", "罗志强", "董杨兴", "李伟"];// 显示学生数量countEl.textContent = names.length;// 随机数生成函数function getRandom(min, max) {return Math.floor(Math.random() * (max - min + 1) + min);}// 生成随机颜色function getRandomColor() {const r = Math.floor(Math.random() * 256);const g = Math.floor(Math.random() * 256);const b = Math.floor(Math.random() * 256);const a = Math.random().toFixed(2);return {bg: `rgba(${r},${g},${b},${a})`,text: `rgb(${g},${r},${b})`};}// 按钮点击事件btn.addEventListener('click', () => {// 生成随机颜色const colors = getRandomColor();// 随机选择学生const randomIndex = getRandom(0, names.length - 1);const selectedStudent = names[randomIndex];// 添加动画效果box.style.opacity = '0';box.style.transform = 'scale(0.9)';setTimeout(() => {// 应用样式和内容box.style.backgroundColor = colors.bg;box.textContent = selectedStudent;box.style.color = colors.text;// 恢复动画box.style.opacity = '1';box.style.transform = 'scale(1)';}, 300);});// 添加键盘支持document.addEventListener('keydown', (e) => {if (e.code === 'Space' || e.key === ' ') {btn.click();}});// 初始显示const initialColors = getRandomColor();box.style.backgroundColor = initialColors.bg;box.style.color = initialColors.text;</script>
</body>
</html>

效果展示:

代码说明 

  1. 响应式设计

    • 使用媒体查询适配移动设备

    • 设置最大宽度防止大屏显示问题

  2. 视觉增强

    • 添加渐变背景和阴影效果

    • 使用卡片式设计增强层次感

    • 添加边框和圆角提升质感

  3. 动画效果

    • 添加过渡动画使颜色变化更平滑

    • 点击时添加缩放效果增强交互感

  4. 功能扩展

    • 显示学生总数

    • 添加键盘支持(空格键触发)

    • 添加信息面板

  5. 代码优化

    • 使用现代DOM查询方法(getElementById)

    • 添加事件监听器替代onclick属性

    • 封装颜色生成函数

    • 添加详细注释

学习要点总结

  1. Math对象的实际应用

    • Math.random() 生成随机数

    • Math.floor() 向下取整

    • 组合使用生成指定范围的随机数

  2. CSS布局技巧

    • Flexbox实现居中布局

    • 视口单位(vh)的使用

    • 复杂背景和阴影效果

  3. 颜色模型理解

    • RGB和RGBA的区别与应用

    • 颜色对比度的重要性

    • 动态生成CSS颜色值

  4. DOM操作

    • 获取页面元素

    • 修改元素内容和样式

    • 添加事件监听器

  5. 响应式设计原则

    • 媒体查询的使用

    • 相对单位的应用

    • 移动优先的设计思想

        这个案例展示了如何将JavaScript基础知识(特别是Math对象)应用到实际项目中,通过组合HTML、CSS和JavaScript创建一个功能完整且视觉吸引人的应用。

http://www.dtcms.com/a/298815.html

相关文章:

  • 肺癌预测模型实战案例
  • C51:用DS1302时钟读取和设置时间
  • 静电释放检测误报率↓79%:陌讯多模态融合算法实战解析
  • 算法:数组part02: 209. 长度最小的子数组 + 59.螺旋矩阵II + 代码随想录补充58.区间和 + 44. 开发商购买土地
  • 2025年ASOC SCI2区TOP,无人机集群路径规划与任务分配的组合优化在多障碍战场环境中的应用,深度解析+性能实测
  • 汽车功能安全 -- TC3xx Error Pin监控机制
  • Post-Training on PAI (5): PAI-EasyDistill, PAI 自研大模型蒸馏框架
  • JAVA知识点(二):数据库
  • rk3588跑通速腾雷达RS16的ros点云读取
  • 装修进度管理系统功能对比:主流工具9选
  • Apipost:离线可用+AI全栈覆盖,国产API开发协作工具新标杆
  • HTTP响应状态码详解
  • 通过Deepseek找工作
  • java-方法的综合练习
  • 屏幕适配--像素篇
  • 100条常用SQL语句大全
  • Linux系统编程——进程
  • 两个MCU互联采集数据
  • kubesphere安装使用
  • 手写数组洗牌算法
  • Vue2 element cascader级联选择器懒加载编辑时回显数据
  • 【VLAs篇】06:从动作词元化视角谈VLA模型的综述
  • 异常(全)
  • which soffice soffice not found
  • Wordpress主题配置
  • 2025年7月24日·AI今日头条
  • KNN算法:从原理到实战全解析
  • Execel文档批量替换标签实现方案
  • day33:零基础学嵌入式之网络——TCP并发服务器
  • 基于javaweb的医院挂号系统