HTML Textarea
上一课用 form="id" 与 form* 讲归属与提交路由。textarea 是另一件事:用于留言与备注的多行文本控件。单行 input 不适合作段落。用户需要不止一行时用 textarea。
为何需要 textarea
联系表单、工单、简介与评价需要可滚动高度。textarea 把该文本作为单个命名字段提交。仍需要 label、name 与尺寸提示——但内容在标签之间,不像 input 的 value。
直接回答
1)写带 id、name、rows 的 textarea。2)用 for 连接 label。3)默认文本放在标签之间——不是 value。4)可选 placeholder、maxlength、readonly、disabled、required、wrap。5)这是多行输入——不是上一课的 form= 关联。
📊 Textarea attributes beginners use
| Attribute | Role | Beginner tip |
|---|---|---|
| name | Submit key | Required if the text should post with the form |
| id | Label hook | Match label for= for accessible naming |
| rows | Visible height hint | Lines of height before scrolling |
| cols | Visible width hint | Prefer CSS width for responsive layouts |
| placeholder | Soft hint | Disappears when the user types |
| maxlength | Character cap | Browser-enforced upper bound |
| readonly / disabled | Lock vs mute | readonly still submits; disabled usually does not |
| wrap | Soft/hard wrap | Affects how line breaks are submitted (soft vs hard) |
反馈表单:带标签的留言框
简短反馈把邮箱当作单行 input、留言当作 textarea。起始文字在标签之间。
<form action="/feedback" method="post">
<label for="email">Email</label>
<input id="email" name="email" type="email" required>
<label for="msg">Message</label>
<textarea id="msg" name="msg" rows="6" cols="40"
placeholder="What went well? What can improve?">Thanks for reading —</textarea>
<button type="submit">Send feedback</button>
</form>
阅读反馈示例
- 多行控件是 textarea,不是 input
- id 与 label for 配对
- name 是提交段落的键
- rows/cols 提示尺寸
- 默认文本在标签之间
- 保持标签清晰
- 此处不需要 form=——字段已在 form 内
尺寸、上限与 wrap
第二个示例:带 maxlength、wrap=soft 的简介,并用 CSS 代替 cols。只读摘要用 readonly。
<label for="bio">Short bio</label>
<textarea id="bio" name="bio" rows="4" maxlength="280"
wrap="soft"
style="width:100%; max-width:28rem; resize:vertical;"
placeholder="Up to 280 characters"></textarea>
<label for="summary">Auto summary (read-only)</label>
<textarea id="summary" name="summary" rows="3" readonly>Generated preview — edit the bio above.</textarea>
阅读尺寸示例
- maxlength 限制长度
- wrap=soft 用于视觉换行而非 hard
- CSS width 与 resize 细化
- readonly 可见但不可编辑
- 提交仍需要 name
- 下一课:用 select 从列表选择
选择 textarea 还是 input
- 短的一行:input
- 段落/留言:textarea
- 用 rows 与 CSS 定尺寸;cols 偏旧
- 默认内容在标签之间——不是 value
- 始终要 label 与 name
- 可能时嵌在 form 内
- 勿与 formaction/归属混淆
练习——搭建并调整尺寸
- 复制反馈;改标签之间的文字
- 减小 rows
- 添加 maxlength
- 用 CSS width 替换 cols
- 短暂试用 value 再删掉
- 写一句:textarea 在标签之间;input 用 value
- 列表选择留给下一课 select
易错点
- 把默认文本写在 value 而不是标签之间
- 忘记 name
- 没有 label
- 需要多行却用单行 input
- 与 form=/formaction 混淆
- 仅靠 cols 做响应宽度
- 该用 readonly 却用了 disabled
小结
- textarea = 多行文本
- label,通常还有 name
- 默认文本在标签之间
- rows/CSS;可选 maxlength、placeholder、readonly
- 不是上一课的表单关联属性
- 下一课:select
🧠 测试您的知识
测试您的知识
通过这个互动测验挑战自己,看看你对这个主题的理解程度如何
📝 说明
- 仔细阅读每个问题
- 为每个问题选择最佳答案
- 您可以随时重新参加测验
- 您的进度将显示在顶部