<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
xmlns:content="http://purl.org/rss/1.0/modules/content/"
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
xmlns:atom="http://www.w3.org/2005/Atom"
xmlns:wfw="http://wellformedweb.org/CommentAPI/">
<channel>
<title>Jack个人博客</title>
<link>https://blog.hkmre.top/</link>
<atom:link href="https://blog.hkmre.top/index.php/feed/" rel="self" type="application/rss+xml" />
<language>zh-CN</language>
<description>Your description here.</description>
<lastBuildDate>Sun, 31 Aug 2025 21:22:00 +0800</lastBuildDate>
<pubDate>Sun, 31 Aug 2025 21:22:00 +0800</pubDate>
<item>
<title>JS 快速入门：从 HTML/CSS 到交互网页的基础指南</title>
<link>https://blog.hkmre.top/index.php/archives/13/</link>
<guid>https://blog.hkmre.top/index.php/archives/13/</guid>
<pubDate>Sun, 31 Aug 2025 21:22:00 +0800</pubDate>
<dc:creator>Jack</dc:creator>
<description><![CDATA[JS 快速学习入门：从 HTML/CSS 到交互网页的进阶指南对于刚学完 HTML 和 CSS 的小伙伴来说，JS（JavaScript）是让网页 “动起来” 的关键 —— 它能实现表单验证、动...]]></description>
<content:encoded xml:lang="zh-CN"><![CDATA[
<p><img src="https://blog.hkmre.top/usr/uploads/2025/08/3175217379.jpg" alt="c7b5eaa84aefddcf91a0f051102c296d.jpg" title="c7b5eaa84aefddcf91a0f051102c296d.jpg"></p><h1>JS 快速学习入门：从 HTML/CSS 到交互网页的进阶指南</h1><p>对于刚学完 HTML 和 CSS 的小伙伴来说，JS（JavaScript）是让网页 “动起来” 的关键 —— 它能实现表单验证、动态内容更新、交互效果等 HTML/CSS 无法完成的功能。这篇文章将带你跳过复杂概念，聚焦 “实用派” 入门：从环境搭建到语法核心，再到结合网页的实战案例，帮你快速掌握 JS 基础并上手开发。</p><h2>一、先搞懂：JS 怎么和 HTML/CSS 配合？</h2><p>在学语法前，先明确 JS 在网页中的 “位置” 和运行方式，这是衔接 HTML/CSS 的核心。</p><h3>1. JS 的 3 种引入方式（直接用 HTML 写）</h3><p>和 CSS 的内联、内嵌、外部引入类似，JS 也有 3 种嵌入网页的方式，新手建议从 “外部引入” 开始（便于维护）。</p><h4>（1）内嵌式（写在 HTML 的<code>&lt;script&gt;</code>标签里）</h4><p>直接在 HTML 文件中用<code>&lt;script&gt;</code>包裹 JS 代码，通常放在<code>&lt;body&gt;</code>末尾（确保 HTML 加载完再执行 JS）：</p><pre><code>&lt;!DOCTYPE html&gt;

&lt;html&gt;

&lt;body&gt;

&lt;h1 id=&quot;title&quot;&gt;Hello HTML/CSS!\&lt;/h1&gt;

&lt;!-- JS放在body末尾 --&gt;

&lt;script&gt;

   // 这里写JS代码：修改h1的内容

   document.getElementById(&quot;title&quot;).innerText = &quot;Hello JS!&quot;;

&lt;/script&gt;

&lt;/body&gt;

&lt;/html&gt;</code></pre><h4>（2）外部引入（推荐！写在单独的.js 文件里）</h4><ol><li>新建一个<code>index.js</code>文件（和 HTML 同目录）；</li><li>在 HTML 中用<code>&lt;script src=&quot;路径&quot;&gt;</code>引入：</li></ol><pre><code>&lt;!-- HTML文件 --&gt;

&lt;body&gt;

&lt;h1 id=&quot;title&quot;&gt;Hello HTML/CSS!\&lt;/h1&gt;

&lt;!-- 引入外部JS --&gt;

&lt;script src=&quot;index.js&quot;&gt;&lt;/script&gt;

&lt;/body&gt;</code></pre><pre><code>//index.js文件

document.getElementById(&quot;title&quot;).innerText = &quot;JS从外部来！&quot;;</code></pre><h4>（3）内联式（写在 HTML 标签的属性里，不推荐）</h4><p>直接把 JS 写在<code>onclick</code>等属性中，仅适合简单场景：</p><pre><code>&lt;button onclick=&quot;alert('你点我了！')&quot;&gt;点我试试\&lt;/button&gt;</code></pre><h3>2. 调试工具：用浏览器控制台看效果</h3><p>写 JS 时难免出错，浏览器的 “控制台” 是调试神器：</p><ol><li>打开网页，按<code>F12</code>或右键 “检查”；</li><li>切换到 “Console”（控制台）面板：</li></ol><ul><li>直接输入 JS 代码按回车，实时看结果；</li><li>代码出错时，这里会显示错误原因和行数。</li></ul><h2>二、JS 语法核心：30 分钟掌握最常用基础</h2><p>JS 语法和 HTML/CSS 不同，但核心基础很简单，重点记 “实用高频” 的内容即可。</p><h3>1. 变量与数据类型：存储数据的 “容器”</h3><p>变量是用来存储数据的，比如用户输入的内容、计算结果等。</p><h4>（1）声明变量：3 个关键字</h4><table><thead><tr><th>关键字</th><th>特点</th><th>推荐场景</th></tr></thead><tbody><tr><td><code>let</code></td><td>可修改、块级作用域（最常用）</td><td>存储会变化的值（如计数器、用户输入）</td></tr><tr><td><code>const</code></td><td>不可修改（常量）</td><td>存储固定值（如网址、固定参数）</td></tr><tr><td><code>var</code></td><td>全局作用域（旧语法，不推荐）</td><td>尽量不用</td></tr></tbody></table><p><strong>示例：结合网页的变量使用</strong></p><pre><code>// 1. 存储固定的网页标题（用const）

const pageTitle = &quot;我的第一个JS网页&quot;;

// 2. 存储用户输入的用户名（用let，因为会变化）

let username = document.getElementById(&quot;username&quot;).value;

// 3. 修改变量的值（let可以改，const不行）

username = &quot;新用户名&quot;;</code></pre><h4>（2）5 种常用数据类型</h4><p>不用死记，通过例子理解：</p><pre><code>let num = 100;          // 数字（整数、小数都算）

let str = &quot;Hello JS&quot;;   // 字符串（用单引号或双引号包裹）

let isShow = true;      // 布尔值（只有true/false两种）

let arr = [1, 2, 3];    // 数组（存储多个值）

let obj = {name: &quot;张三&quot;, age: 20}; // 对象（存储键值对，如用户信息）</code></pre><p><strong>举一反三</strong>：用变量存储网页中的 “商品价格” 和 “商品列表”</p><pre><code>// 商品价格（数字类型）

let price = 99.9;

// 商品列表（数组类型，每个元素是对象）

let goodsList = [

 {name: &quot;T恤&quot;, price: 59},

 {name: &quot;裤子&quot;, price: 89}

];</code></pre><h3>2. 运算符：做计算或判断</h3><p>和数学中的运算符类似，重点记 “赋值”“比较”“逻辑” 三类。</p><h4>（1）赋值运算符（给变量赋值）</h4><pre><code>let a = 10;

a += 5; // 等价于 a = a + 5 → 结果15

a *= 2; // 等价于 a = a * 2 → 结果30</code></pre><h4>（2）比较运算符（判断两个值的关系）</h4><p>常用于 “条件判断”，返回<code>true</code>或<code>false</code>：</p><pre><code>let x = 10;

console.log(x &gt; 5);  // true

console.log(x === 10); // 全等（值和类型都一样，推荐用===不用==）

console.log(x != 8); // true</code></pre><h4>（3）逻辑运算符（组合多个判断）</h4><table><thead><tr><th>运算符</th><th>作用</th><th>示例</th><th>结果</th></tr></thead><tbody><tr><td><code>&amp;&amp;</code></td><td>与（两个都为 true 才 true）</td><td><code>(x&gt;5) &amp;&amp; (x&lt;15)</code></td><td>true</td></tr><tr><td><code>\</code></td><td> </td><td><code>\</code></td><td>或（一个为 true 就 true）</td></tr><tr><td><code>!</code></td><td>非（取反）</td><td><code>!(x===10)</code></td><td>false</td></tr></tbody></table><h3>3. 条件语句：让 JS “做选择”</h3><p>根据不同条件执行不同代码，最常用<code>if...else</code>和<code>switch</code>。</p><h4>（1）if...else（多条件判断）</h4><p><strong>示例：网页表单验证（判断用户名是否为空）</strong></p><pre><code>&lt;!-- HTML：用户名输入框 --&gt;

&lt;input type=&quot;text&quot; id=&quot;username&quot; placeholder=&quot;请输入用户名&quot;&gt;

&lt;button onclick=&quot;checkUsername()&quot;&gt;提交&lt;/button&gt;</code></pre><pre><code>// JS：验证函数

function checkUsername() {

 let username = document.getElementById(&quot;username&quot;).value;

 if (username === &quot;&quot;) { // 条件1：为空

   alert(&quot;用户名不能为空！&quot;);

 } else if (username.length &lt; 3) { // 条件2：长度不够

   alert(&quot;用户名至少3个字符！&quot;);

 } else { // 都不满足（条件成立）

   alert(&quot;用户名合法！&quot;);

 }

}</code></pre><h4>（2）switch（固定值匹配）</h4><p><strong>示例：根据用户选择的 “颜色” 修改网页背景</strong></p><pre><code>&lt;select id=&quot;colorSelect&quot; onchange=&quot;changeBg()&quot;&gt;

&lt;option value=&quot;white&quot;&gt;白色&lt;/option&gt;

&lt;option value=&quot;lightblue&quot;&gt;蓝色&lt;/option&gt;

&lt;option value=&quot;lightgreen&quot;&gt;绿色&lt;/option&gt;

&lt;/select&gt;</code></pre><pre><code>function changeBg() {

 let color = document.getElementById(&quot;colorSelect&quot;).value;

 switch (color) {

   case &quot;white&quot;:

     document.body.style.backgroundColor = &quot;white&quot;;

     break; // 必须加break，否则会继续执行下一个case

   case &quot;lightblue&quot;:

     document.body.style.backgroundColor = &quot;lightblue&quot;;

     break;

   case &quot;lightgreen&quot;:

     document.body.style.backgroundColor = &quot;lightgreen&quot;;

     break;

 }

}</code></pre><p><strong>举一反三</strong>：扩展表单验证，增加 “密码是否一致” 的判断</p><pre><code>&lt;input type=&quot;password&quot; id=&quot;pwd1&quot; placeholder=&quot;密码&quot;&gt;

&lt;input type=&quot;password&quot; id=&quot;pwd2&quot; placeholder=&quot;确认密码&quot;&gt;

&lt;button onclick=&quot;checkPwd()&quot;&gt;验证密码&lt;/button&gt;</code></pre><pre><code>function checkPwd() {

 let pwd1 = document.getElementById(&quot;pwd1&quot;).value;

 let pwd2 = document.getElementById(&quot;pwd2&quot;).value;

 if (pwd1 === &quot;&quot;) {

   alert(&quot;请输入密码！&quot;);

 } else if (pwd1 !== pwd2) {

   alert(&quot;两次密码不一致！&quot;);

 } else {

   alert(&quot;密码一致！&quot;);

 }

}</code></pre><h3>4. 循环语句：重复执行代码</h3><p>当需要 “批量处理”（如遍历数组、生成列表）时用循环，最常用<code>for</code>和<code>for...of</code>。</p><h4>（1）for 循环（适合已知循环次数）</h4><p><strong>示例：根据数组生成网页列表</strong></p><pre><code>&lt;!-- HTML：空列表 --&gt;

&lt;ul id=&quot;goodsList&quot;&gt;&lt;/ul&gt;</code></pre><pre><code>// JS：商品数组

let goods = [&quot;T恤&quot;, &quot;裤子&quot;, &quot;鞋子&quot;, &quot;帽子&quot;];

// 获取列表元素

let list = document.getElementById(&quot;goodsList&quot;);

// for循环遍历数组

for (let i = 0; i &lt; goods.length; i++) {

 // 每次循环添加一个li到列表

 list.innerHTML += `&lt;li&gt;${goods[i]}&lt;/li&gt;`;

}</code></pre><ul><li><code>i</code>是 “计数器”，从 0 开始；</li><li><code>i &lt; goods.length</code>：循环条件（只要 i 小于数组长度就继续）；</li><li><code>i++</code>：每次循环后 i 加 1。</li></ul><h4>（2）for...of 循环（适合遍历数组 / 字符串，更简洁）</h4><pre><code>let goods = [&quot;T恤&quot;, &quot;裤子&quot;, &quot;鞋子&quot;];

for (let item of goods) {

&amp;#x20; console.log(item); // 依次输出：T恤、裤子、鞋子

}</code></pre><p><strong>举一反三</strong>：用循环计算数组中 “商品总价”</p><pre><code>let goodsPrice = [59, 89, 129, 39];

let total = 0;

for (let price of goodsPrice) {

 total += price; // 累加每个商品价格

}

console.log(&quot;总价：&quot; + total); // 输出：316</code></pre><h2>三、JS 核心：函数与方法（重点！）</h2><p>函数是 “可重复调用的代码块”，方法是 “对象中的函数”。掌握常用函数和方法，能大幅提升开发效率。</p><h3>1. 自定义函数：把重复代码 “封装” 起来</h3><p>当一段代码需要多次执行（如表单验证、样式修改）时，就把它封装成函数。</p><h4>（1）函数的基本语法</h4><pre><code>// 定义函数

function 函数名(参数1, 参数2) {

 // 函数体（要执行的代码）

 return 返回值; // 可选：返回函数执行结果

}

// 调用函数

函数名(实参1, 实参2);</code></pre><h4>（2）示例：封装 “计算两个数之和” 的函数</h4><pre><code>// 定义函数：参数a和b，返回它们的和

function add(a, b) {

 return a + b;

}

// 调用函数：传入实参3和5，接收返回值

let result = add(3, 5);

console.log(result); // 输出8

// 结合网页：点击按钮计算总价

function calculateTotal(price, count) {

 return price * count;

}</code></pre><pre><code>&lt;button onclick=&quot;alert('总价：' + calculateTotal(99, 2))&quot;&gt;计算2件商品总价&lt;/button&gt;</code></pre><p><strong>举一反三</strong>：封装 “修改元素样式” 的函数（可复用给多个元素）</p><pre><code>// 定义函数：参数1=元素ID，参数2=样式对象

function setStyle(elementId, styles) {

 let elem = document.getElementById(elementId);

 // 遍历样式对象，批量设置样式

 for (let key in styles) {

   elem.style\[key] = styles\[key];

 }

}

// 调用函数：修改h1和p的样式

setStyle(&quot;title&quot;, {color: &quot;red&quot;, fontSize: &quot;24px&quot;});

setStyle(&quot;content&quot;, {lineHeight: &quot;1.8&quot;, color: &quot;#333&quot;});</code></pre><h3>2. 常用内置函数（JS 自带，直接用）</h3><p>无需定义，直接调用的函数，重点记这 3 个：</p><table><thead><tr><th>函数</th><th>作用</th><th>示例</th></tr></thead><tbody><tr><td><code>alert(内容)</code></td><td>弹出提示框</td><td><code>alert(&quot;操作成功！&quot;)</code></td></tr><tr><td><code>console.log(内容)</code></td><td>在控制台输出（调试用）</td><td><code>console.log(&quot;当前值：&quot; + x)</code></td></tr><tr><td><code>prompt(提示语, 默认值)</code></td><td>弹出输入框，返回用户输入的内容</td><td><code>let age = prompt(&quot;请输入年龄&quot;, 18)</code></td></tr></tbody></table><h3>3. 常用对象方法（数组、字符串、DOM）</h3><p>方法是 “对象。方法名 ()” 的形式，重点掌握数组、字符串和 DOM 操作的方法。</p><h4>（1）数组方法（处理批量数据）</h4><table><thead><tr><th>方法</th><th>作用</th><th>示例</th><th>结果</th></tr></thead><tbody><tr><td><code>push(元素)</code></td><td>向数组末尾添加元素</td><td><code>let arr = [1,2]; arr.push(3)</code></td><td>[1,2,3]</td></tr><tr><td><code>filter(条件)</code></td><td>筛选符合条件的元素</td><td><code>arr.filter(item =&gt; item &gt; 2)</code></td><td>[3]</td></tr><tr><td><code>map(处理函数)</code></td><td>对每个元素做处理，返回新数组</td><td><code>arr.map(item =&gt; item * 2)</code></td><td>[2,4,6]</td></tr><tr><td><code>join(分隔符)</code></td><td>把数组转成字符串</td><td><code>arr.join(&quot;-&quot;)</code></td><td>"1-2-3"</td></tr></tbody></table><p><strong>示例：用数组方法筛选网页中的 “低价商品”</strong></p><pre><code>let goods = [

 {name: &quot;T恤&quot;, price: 59},

 {name: &quot;裤子&quot;, price: 89},

 {name: &quot;袜子&quot;, price: 9}

];

// 筛选价格&lt;30的商品

let cheapGoods = goods.filter(item =&gt; item.price &lt; 30);

console.log(cheapGoods); // 输出：[{name: &quot;袜子&quot;, price: 9}]</code></pre><h4>（2）字符串方法（处理文本）</h4><table><thead><tr><th>方法</th><th>作用</th><th>示例</th><th>结果</th></tr></thead><tbody><tr><td><code>length</code></td><td>获取字符串长度</td><td><code>&quot;hello&quot;.length</code></td><td>5</td></tr><tr><td><code>includes(子串)</code></td><td>判断是否包含子串</td><td><code>&quot;hello&quot;.includes(&quot;he&quot;)</code></td><td>true</td></tr><tr><td><code>trim()</code></td><td>去除首尾空格</td><td><code>&quot;  js  &quot;.trim()</code></td><td>"js"</td></tr><tr><td><code>replace(旧值, 新值)</code></td><td>替换字符</td><td><code>&quot;hello&quot;.replace(&quot;h&quot;, &quot;H&quot;)</code></td><td>"Hello"</td></tr></tbody></table><p><strong>示例：处理用户输入的 “手机号”（去除空格）</strong></p><pre><code>let phone = document.getElementById(&quot;phone&quot;).value;

// 去除空格并判断长度是否为11

let cleanPhone = phone.trim();

if (cleanPhone.length !== 11) {

 alert(&quot;手机号格式错误！&quot;);

}</code></pre><h4>（3）DOM 操作方法（核心！控制 HTML 元素）</h4><p>DOM（文档对象模型）是 JS 操作 HTML 的接口，重点记 “获取元素”“修改内容 / 样式”“绑定事件” 三类方法。</p><table><thead><tr><th>操作类型</th><th>方法</th><th>示例</th></tr></thead><tbody><tr><td><strong>获取元素</strong></td><td><code>getElementById(id)</code></td><td><code>document.getElementById(&quot;title&quot;)</code>（通过 ID 获取，最常用）</td></tr><tr><td> </td><td><code>querySelector(选择器)</code></td><td><code>document.querySelector(&quot;.box&quot;)</code>（支持 CSS 选择器，如.class、#id）</td></tr><tr><td><strong>修改内容</strong></td><td><code>innerText</code></td><td>纯文本内容（<code>elem.innerText = &quot;新文本&quot;</code>）</td></tr><tr><td> </td><td><code>innerHTML</code></td><td>带 HTML 标签的内容（<code>elem.innerHTML = &quot;&lt;b&gt;加粗&lt;/b&gt;&quot;</code>）</td></tr><tr><td><strong>修改样式</strong></td><td><code>style.样式名</code></td><td><code>elem.style.color = &quot;red&quot;</code>（样式名用驼峰式，如 fontSize）</td></tr><tr><td> </td><td><code>classList.add/remove</code></td><td>操作 CSS 类（<code>elem.classList.add(&quot;active&quot;)</code>）</td></tr><tr><td><strong>绑定事件</strong></td><td><code>addEventListener(事件名, 函数)</code></td><td>动态绑定事件（比内联 onclick 更灵活）</td></tr></tbody></table><p><strong>综合示例：点击按钮切换网页主题（DOM + 函数 + 样式）</strong></p><pre><code>&lt;!-- HTML --&gt;

&lt;button id=&quot;themeBtn&quot;&gt;切换深色模式\&lt;/button&gt;

&lt;div class=&quot;content&quot;&gt;这是网页内容\&lt;/div&gt;

&lt;!-- CSS --&gt;

&lt;style&gt;

 .light { background: white; color: #333; }

 .dark { background: #333; color: white; }

&lt;/style&gt;

&lt;!-- JS --&gt;

&lt;script&gt;

 // 1. 获取元素

 let btn = document.getElementById(&quot;themeBtn&quot;);

 let content = document.querySelector(&quot;.content&quot;);

 let isDark = false; // 标记当前是否为深色模式

 // 2. 绑定点击事件（用addEventListener）

 btn.addEventListener(&quot;click&quot;, function() {

   if (isDark) {

     // 切换浅色模式

     document.body.className = &quot;light&quot;;

     btn.innerText = &quot;切换深色模式&quot;;

     isDark = false;

   } else {

     // 切换深色模式

     document.body.className = &quot;dark&quot;;

     btn.innerText = &quot;切换浅色模式&quot;;

     isDark = true;

   }

 });

&lt;/script&gt;</code></pre><p><strong>举一反三</strong>：扩展成 “点击按钮显示 / 隐藏密码”</p><pre><code>&lt;input type=&quot;password&quot; id=&quot;pwd&quot;&gt;

&lt;button id=&quot;togglePwd&quot;&gt;显示密码\&lt;/button&gt;</code></pre><pre><code>let pwd = document.getElementById(&quot;pwd&quot;);

let btn = document.getElementById(&quot;togglePwd&quot;);

let isShow = false;

btn.addEventListener(&quot;click&quot;, function() {

 if (isShow) {

   pwd.type = &quot;password&quot;; // 隐藏密码

   btn.innerText = &quot;显示密码&quot;;

   isShow = false;

 } else {

   pwd.type = &quot;text&quot;; // 显示密码

   btn.innerText = &quot;隐藏密码&quot;;

   isShow = true;

 }

});</code></pre><h2>四、实战案例：用 JS 写一个简单的待办清单</h2><p>结合前面的所有知识点，我们来写一个可 “添加”“删除” 待办的网页，巩固 JS 基础。</p><h3>完整代码（HTML+CSS+JS）</h3><pre><code>&lt;!DOCTYPE html&gt;

&lt;html&gt;

&lt;head&gt;

&lt;title&gt;JS待办清单&lt;/title&gt;

&lt;style&gt;

   .todo-container { width: 400px; margin: 20px auto; }

   #todoInput { width: 280px; padding: 8px; }

   #addBtn { padding: 8px 16px; background: #008cba; color: white; border: none; cursor: pointer; }

   .todo-item { display: flex; justify-content: space-between; margin: 8px 0; padding: 8px; border: 1px solid #eee; }

   .deleteBtn { color: red; border: none; background: none; cursor: pointer; }

&lt;/style&gt;

&lt;/head&gt;

&lt;body&gt;

&lt;div class=&quot;todo-container&quot;&gt;

&lt;h2&gt;待办清单&lt;/h2&gt;

&lt;input type=&quot;text&quot; id=&quot;todoInput&quot; placeholder=&quot;请输入待办事项&quot;&gt;

&lt;button id=&quot;addBtn&quot;&gt;添加&lt;/button&gt;

&lt;div id=&quot;todoList&quot;&gt;&lt;/div&gt;

&lt;/div&gt;

&lt;script&gt;

   // 1. 获取元素

   let input = document.getElementById(&quot;todoInput&quot;);

   let addBtn = document.getElementById(&quot;addBtn&quot;);

   let todoList = document.getElementById(&quot;todoList&quot;);

   // 2. 添加待办事项的函数

   function addTodo() {

     let text = input.value.trim(); // 去除空格

     if (text === &quot;&quot;) { // 验证非空

       alert(&quot;请输入待办事项！&quot;);

       return; // 为空则不执行后续代码

     }

     // 创建待办项（用innerHTML添加HTML）

     todoList.innerHTML += `

       &lt;div class=&quot;todo-item&quot;&gt;

         &lt;span&gt;${text}&lt;/span&gt;

         &lt;button class=&quot;deleteBtn&quot;&gt;删除&lt;/button&gt;

       &lt;/div&gt;

     `;

     // 清空输入框

     input.value = &quot;&quot;;

     // 给新添加的删除按钮绑定事件（委托给父元素）

     bindDeleteEvent();

   }

   // 3. 删除待办事项的函数

   function bindDeleteEvent() {

     // 获取所有删除按钮

     let deleteBtns = document.querySelectorAll(&quot;.deleteBtn&quot;);

     // 遍历按钮，绑定点击事件

     for (let btn of deleteBtns) {

       btn.addEventListener(&quot;click&quot;, function() {

         // 删除当前按钮的父元素（todo-item）

         this.parentElement.remove();

       });

     }

   }

   // 4. 绑定添加按钮的点击事件

   addBtn.addEventListener(&quot;click&quot;, addTodo);

   // 支持按Enter键添加

   input.addEventListener(&quot;keydown&quot;, function(e) {

     if (e.key === &quot;Enter&quot;) {

       addTodo();

     }

   });

 &lt;/script&gt;

&lt;/body&gt;

&lt;/html&gt;</code></pre><h3>案例要点解析</h3><ol><li><strong>DOM 操作</strong>：用<code>getElementById</code>获取输入框和按钮，用<code>innerHTML</code>动态生成待办项；</li><li><strong>函数封装</strong>：把 “添加”“删除” 功能分别封装成<code>addTodo()</code>和<code>bindDeleteEvent()</code>；</li><li><strong>事件绑定</strong>：既用了<code>addEventListener</code>绑定点击 / 键盘事件，又处理了 “动态元素的事件委托”；</li><li><strong>表单验证</strong>：用<code>trim()</code>去除空格，判断输入是否为空。</li></ol><h2>五、新手快速上手的 3 个建议</h2><ol><li><strong>“先抄后改”</strong>：先复制本文的示例代码，运行成功后再修改（如改文字、改样式、加条件），逐步理解逻辑；</li><li><strong>聚焦 “网页交互”</strong>：不要纠结于纯 JS 语法题，多写 “点击按钮、修改内容、表单验证” 等网页场景的代码；</li><li><strong>善用文档</strong>：遇到不懂的方法，查<a href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript">MDN 文档</a>（最权威，有中文版本）。</li></ol><p>通过本文的学习，你已经掌握了 JS 和 HTML/CSS 的配合方式、核心语法、常用函数 / 方法，以及实战案例的开发思路。接下来就动手修改案例，比如给待办清单加 “完成状态切换”，或者写一个简单的计算器 —— 多练多改，JS 入门其实很简单！</p>
]]></content:encoded>
<slash:comments>1</slash:comments>
<comments>https://blog.hkmre.top/index.php/archives/13/#comments</comments>
<wfw:commentRss>https://blog.hkmre.top/index.php/feed/</wfw:commentRss>
</item>
<item>
<title>网格布局两行代码css,完美适配任何屏幕</title>
<link>https://blog.hkmre.top/index.php/archives/9/</link>
<guid>https://blog.hkmre.top/index.php/archives/9/</guid>
<pubDate>Wed, 06 Aug 2025 20:10:00 +0800</pubDate>
<dc:creator>Jack</dc:creator>
<description><![CDATA[用 CSS Grid 快速实现自适应卡片布局：两行代码搞定响应式设计在网页开发中，“一排展示多个卡片，且卡片能根据屏幕宽度自动调整数量与尺寸”是非常常见的需求。例如产品列表、图片画廊、内容卡片等...]]></description>
<content:encoded xml:lang="zh-CN"><![CDATA[
<p><img src="https://blog.hkmre.top/usr/uploads/2025/08/3265167721.jpg" alt="112858-172714853802c6.jpg" title="112858-172714853802c6.jpg"></p><h1>用 CSS Grid 快速实现自适应卡片布局：两行代码搞定响应式设计</h1><p>在网页开发中，“一排展示多个卡片，且卡片能根据屏幕宽度自动调整数量与尺寸”是非常常见的需求。例如产品列表、图片画廊、内容卡片等场景，都需要这种灵活的自适应布局。</p><p>传统实现方式往往依赖复杂的 Flexbox 嵌套或大量媒体查询（Media Query），代码冗余且维护成本高。而使用 CSS Grid 布局，仅需给父容器添加两行核心 CSS，即可完美满足需求。</p><h2>一、核心实现代码</h2><p>以下是完整代码示例，核心逻辑集中在父元素的 <code>grid</code> 相关属性中：</p><pre><code class="lang-css">/* 父容器：控制网格布局的核心 */
.grid-container {
  display: grid; /* 1. 启用 Grid 布局 */
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); /* 2. 定义列规则 */
  gap: 16px; /* 可选：添加卡片间距，提升视觉效果 */
  padding: 16px; /* 可选：添加容器内边距，避免卡片贴边 */
}

/* 子元素：卡片样式 */
.grid-item {
  height: 200px; /* 固定卡片高度 */
  background-color: rgb(141, 141, 255); /* 卡片背景色 */
  border-radius: 10px; /* 圆角设计，优化视觉 */
  display: flex; /* 可选：方便内部内容居中 */
  align-items: center;
  justify-content: center;
  color: #fff; /* 可选：文字颜色 */
}</code></pre><h2>二、核心代码拆解：<code>grid-template-columns</code></h2><p>实现自适应的关键在于 <code>grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));</code>，我们将其拆分为 3 个部分逐一理解：</p><h3>1. 基础属性：<code>grid-template-columns</code></h3><ul><li><strong>作用</strong>：定义网格容器的“列数”和“每列宽度”，是 Grid 布局控制列的核心属性。</li><li><strong>示例</strong>：若写 <code>grid-template-columns: 200px 200px 200px;</code>，则表示容器固定显示 3 列，每列宽 200px（非自适应）。</li></ul><h3>2. 重复规则：<code>repeat(auto-fit, ...)</code></h3><ul><li><code>repeat()</code>：是 CSS Grid 提供的“重复函数”，用于简化“重复相同列/行规则”的写法。语法为 <code>repeat(重复次数, 重复的规则)</code>。</li><li><p><code>auto-fit</code>：是 <code>repeat()</code> 的第一个参数（重复次数），表示“自动计算列数”——根据容器宽度和列宽规则，能放下几列就放几列，空间不足时自动换行。</p><ul><li>屏幕宽 → 列数多（如桌面端显示 4 列）；</li><li>屏幕窄 → 列数少（如移动端显示 1-2 列）。</li></ul></li></ul><h3>3. 列宽规则：<code>minmax(200px, 1fr)</code></h3><ul><li><code>minmax()</code>：是“范围函数”，用于定义一个“最小值”和“最大值”，语法为 <code>minmax(最小值, 最大值)</code>。</li><li><p>具体含义：</p><ul><li><strong>最小值 200px</strong>：每列宽度最小不能小于 200px，当屏幕窄到无法容纳更多列时，触发自动换行（避免卡片被压缩变形）；</li><li><strong>最大值 1fr</strong>：<code>1fr</code> 是 Grid 中的“弹性单位”，代表“剩余空间的等分”。当屏幕宽度有剩余时，每列会自动拉伸，平分剩余空间，让整行卡片填满容器（避免出现空白）。</li></ul></li></ul><h2>三、最终效果总结</h2><p>将上述三部分结合，<code>grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));</code> 的完整作用是：</p><blockquote>网格容器会自动生成列，每列宽度“最小 200px、最大平分剩余空间”；屏幕变宽时自动增加列数，屏幕变窄时自动减少列数并换行，无需写任何媒体查询，即可实现全场景自适应。</blockquote><p>这种写法不仅代码简洁，还能确保布局在任何屏幕尺寸下都保持美观，是实现卡片类自适应布局的“最优解”之一。</p>
]]></content:encoded>
<slash:comments>2</slash:comments>
<comments>https://blog.hkmre.top/index.php/archives/9/#comments</comments>
<wfw:commentRss>https://blog.hkmre.top/index.php/feed/</wfw:commentRss>
</item>
</channel>
</rss>