正在加载...
HTML 表单元素
表单属性细化了 form 标签本身。表单元素是标签内部的零件——标签、文本区、列表、按钮与分组。本课绘制常用工具箱。input 类型下一课讲。
为什么表单元素重要
只有属性的空 form 无法收集答案。用户需要控件。用 textarea 而非单行 input,或用 select 而非自由文本,会改变体验与收到的数据。
直接回答
1) 每个可见控件配 label。2) input 用于多种单行/开关。3) textarea 多行。4) select+option 固定列表。5) button 触发动作。6) fieldset+legend 分组。action/method 仍在外层 form。
📊 Common form pieces
| Element | Role | Beginner tip |
|---|---|---|
| label | Names a control for humans and assistive tech | Match for= to the control id |
| input | Single-line text, email, checks, radios, … | Types catalog is the next lesson |
| textarea | Multi-line text | Prefer over input for bios and messages |
| select / option | Choose from a fixed list | Each option needs a value |
| button | submit, reset, or generic action | Default in a form is often submit — set type explicitly |
| fieldset / legend | Group related controls with a title | legend is the accessible group name — not a plain div |
含混合控件的个人资料 fieldset
小型资料编辑器:一个分组、多行简介、级别下拉、保存按钮。
Profile fieldset with controls
html
HTML Code
<form action="/profile" method="post">
<fieldset>
<legend>Profile</legend>
<label for="bio">Bio</label>
<textarea id="bio" name="bio" rows="4"></textarea>
<label for="level">Level</label>
<select id="level" name="level">
<option value="beginner">Beginner</option>
<option value="middle">Middle</option>
<option value="advanced">Advanced</option>
</select>
<button type="submit">Save</button>
</fieldset>
</form>
读个人资料示例
- fieldset+legend 命名分组
- textarea 更适合简介
- select/option 限制级别
- 每个控件有 id 与 name
- submit 提交整个表单
- action/method 来自上一课
偏好:单选与按钮类型
有时答案互斥。单选共享 name。每个选项保留 label。对比 submit、reset 与 button。
Preferences radios and buttons
html
HTML Code
<form action="/prefs" method="post">
<fieldset>
<legend>Theme</legend>
<label>
<input type="radio" name="theme" value="light" checked>
Light
</label>
<label>
<input type="radio" name="theme" value="dark">
Dark
</label>
</fieldset>
<button type="submit">Save prefs</button>
<button type="reset">Clear</button>
</form>
读偏好示例
- 同 name 的单选构成一组
- 把单选包在 label 里使文字可点
- legend 标题为 Theme
- submit 发送;reset 清空——不是保存
- 其他 input 类型下一课
选择正确控件
- 短答/邮箱/密码:input
- 长文本:textarea
- 固定列表:select 或单选
- 分组区块:fieldset+legend
- 命名:label
- 提交:button type=submit
练习——组装表单元素
- 复制资料示例;改 legend 并加 option
- 临时用 input 替换 textarea
- 第二个 fieldset 放备注
- 主题单选;点击 label
- Clear 再 Save
- 把一个控件移出 form
- 一句话:元素是表单内带标签的控件;form 标签上的属性是另一层
易错点
- 无 label 的控件
- 用 div 标题代替 legend
- submit 或字段在 form 外
- 用单行 input 写长消息
- 忘记 name
- 以为 reset 会保存到服务器
- 以为本课取代 action/method
小结
- 表单元素是 form 内的控件与辅助
- label、input、textarea、select、button、fieldset/legend 覆盖多数入门界面
- 始终加标签;用 fieldset 分组
- 按问题类型选控件
- 表单属性与 input 类型是不同层
- 下一课:input 类型
🧠 测试您的知识
准备开始
测试您的知识
通过这个互动测验挑战自己,看看你对这个主题的理解程度如何
5
问题
70%
及格要求
∞
时间
∞
尝试次数
📝 说明
- 仔细阅读每个问题
- 为每个问题选择最佳答案
- 您可以随时重新参加测验
- 您的进度将显示在顶部