颜色 Changer
你将构建什么
page 使用 colored box and "Change color" button. 每个点击 generates random hex 颜色 and applies 它到 box's background.
学习目标
- Generate random hex 颜色字符串
- 更新元素's inline 样式从 JavaScript
- Use 点击事件监听器到 触发更新
- 理解如何 CSS 属性映射到 样式对象
前置要求
- 字符串 concatenation or template literals
- DOM selection and 事件监听器
步骤
- 1
编写 HTML
创建 div 使用 id and button. div 是颜色目标; button 触发更改.
代码<div id="box" style="width:200px;height:200px;background:#2563eb;"></div> <button id="change">Change color</button>预期结果
blue 200×200 box and button appear on page.
- 2
Generate random hex 颜色
编写函数那个构建 hex 颜色从 six random hex digits. 每个 digit 是 0-15, converted 到 hex 使用 toString(16).
代码function randomColor() { let hex = "#"; for (let i = 0; i < 6; i++) { hex += Math.floor(Math.random() * 16).toString(16); } return hex; }预期结果
Calling randomColor() 返回字符串如 "#3f9a2c" — 有效 hex 颜色.
提示
toString(16) converts 数字 0-15 到单个 hex digit (0-9 or -f).
- 3
Wire button
选择 box and button. On 点击, 设置 box.样式.background 到新 random 颜色. 样式对象映射 directly 到 CSS 属性.
代码const box = document.getElementById("box"); const btn = document.getElementById("change"); btn.addEventListener("click", () => { box.style.background = randomColor(); });预期结果
每个点击更改 box 到新 random 颜色.
- 4
添加输入验证与错误处理
在用户输入处添加验证:检查空值、非数字、负数等异常情况,用 try/catch 或条件判断给出友好提示。健壮的 JS 程序不会因意外输入而崩溃。
代码function safeParse(value) { if (value === null || value === undefined || value === "") { throw new Error("Input is empty"); } const num = Number(value); if (Number.isNaN(num)) { throw new Error(`"${value}" is not a valid number`); } return num; } try { const n = safeParse(userInput); process(n); } catch (err) { console.error(err.message); }预期结果
空输入或非数字输入显示错误消息而非崩溃;合法数字正常处理。
- 5
添加事件监听与交互
为页面元素绑定事件监听器(click、input、keydown 等),让程序响应用户操作。交互性是 JavaScript 在前端的核心价值。
代码const button = document.querySelector("#action-btn"); const input = document.querySelector("#user-input"); button.addEventListener("click", () => { const value = input.value.trim(); if (!value) return; runMainLogic(value); }); input.addEventListener("keydown", (e) => { if (e.key === "Enter") button.click(); });预期结果
点击按钮或按回车键触发主逻辑;空输入被忽略。
自己动手试试
<div id="box" style="width:200px;height:200px;background:#2563eb;"></div>
<button id="change">Change color</button>
<script>
// TODO: randomColor() + wire button
</script><div id="box" style="width:200px;height:200px;background:#2563eb;"></div>
<button id="change">Change color</button>
<script>
function randomColor() {
let hex = "#";
for (let i = 0; i < 6; i++) {
hex += Math.floor(Math.random() * 16).toString(16);
}
return hex;
}
const box = document.getElementById("box");
const btn = document.getElementById("change");
btn.addEventListener("click", () => {
box.style.background = randomColor();
});
</script>你学到了什么
你 generated random hex 字符串 and applied 它通过元素's 样式对象 — 相同方法 used 通过任何 tool 那个更改 appearance 从 JavaScript.
相关资源
相关练习
- DOM 事件 MCQ
测验 on 事件监听器 and 样式对象.
- 字符串 Predict
Predict result 的字符串 concatenation.
相关工具
- 颜色 Tool
Inspect and convert hex 颜色你的 generator produces.
相关速查表
- JavaScript Cheatsheet
Math, 字符串, and DOM 样式语法引用.
相关参考文档
- JavaScript 字符串方法
完整字符串方法引用.
相关错误
- Cannot 读取属性的 空
空元素 selection mistakes.
相关术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
相关错误
用大白话解释常见错误——什么意思、为什么发生、如何修复。
- Cannot 读取属性的 空
空元素 selection mistakes.