别再把 input 写成呆瓜!表单属性这样玩才有人点
60
0
0
HTML 表单,说穿了就是跟用户“要数据”的窗口。
别急着写 <div>、<style>,先把 <input> 的脾气摸透——它才是整个故事的男主。
1. 先写一句能跑的骨架
<form action="/submit" method="post">
<input type="text" name="username" placeholder="起个名字吧">
<input type="submit" value="丢给后台">
</form>就这两行,浏览器立刻给你画出一个框和一个按钮。别的都是锦上添花。
2. 属性全家福,一张表背下来够用半年
| 属性 | 干啥的 | 一句话记忆 |
|---|---|---|
type | 决定键盘弹出的样子 | email 自带 @ 检测,number 只能调出数字键盘 |
name | 后端小哥的暗号 | 没它,表单提交=白送 |
placeholder | 灰色提示语,输入就消失 | 别把标签 <label> 省了,光写它不够友好 |
value | 默认值 | 想给用户“预填”,就写这里 |
required | 留空就拦下 | 浏览器自带小红框,比 JS 省事 |
checked | 默认勾上 | 只对 checkbox / radio 有效 |
disabled | 直接锁死 | 灰色 + 鼠标禁用,数据也不会提交 |
maxlength | 字数刹车 | 手机端尤其好用,省得用户手滑 |
min / max | 数字范围 | 搭配 type="number",秒变“滑杆” |
pattern | 正则守门员 | 例:pattern="\d{4}" 只让输 4 位数字,省一次后端校验 |
3. 一段能直接粘进项目的完整示例
<form action="/register" method="post">
<label>
用户名
<input type="text" name="username" required placeholder="3~12 个字符">
</label>
<label>
密码
<input type="password" name="pwd" required minlength="6">
</label>
<label>
邮箱
<input type="email" name="email" required>
</label>
<label>
年龄
<input type="number" name="age" min="18" max="120">
</label>
<label>
<input type="checkbox" name="agree" required>
已阅读并同意用户协议
</label>
<button type="submit">立即注册</button>
</form>把 <label> 包在外面,点击文字也能聚焦输入框,手机用户会谢你。
4. 三个小坑,顺手埋了
required对type="hidden"无效,别指望它帮你拦。disabled的字段压根不会发回服务器,真想“只读”用readonly。- 手机端想呼出数字键盘,用
type="number"别用type="tel",除非你真的要打电话。
表单写到最后,记住一句话:先让浏览器帮你挡子弹,再让后端补最后一枪。
属性写全了,JS 校验就能省一半,用户也轻快。
0
快来点个赞吧
发表评论
评论列表