别再把表单属性背成单词表:一句人话告诉你它们到底干嘛
106
0
0
表单属性这玩意儿,说穿了就是“给元素贴张便签,让浏览器和后台都能看得懂”。
别背词典,下面直接上场景——哪里卡了,就来翻对应的便签。
1. <form> 身上的五张便签
| 便签 | 日常人话 | 掉坑提醒 |
|---|---|---|
action="/save" | 数据扔到这个地址 | 写错就 404,后台收了个寂寞 |
method="post" | 把数据藏进信封里 | 上传文件、密码必用 post,get 会裸奔到地址栏 |
enctype="multipart/form-data" | 信封里夹带“附件” | 只要有 <input type="file">,就必须换这种信封,否则后台只收到文件名 |
target="_blank" | 返回结果在新标签打开 | 搜索场景常用,注册场景慎用——用户可能关错窗口 |
novalidate | 把浏览器自带的“小红框”关掉 | 想完全自己写校验逻辑再用,不然用户空着也能点提交 |
2. <input> 常用便签速查
type="email"→ 自带“@”检查,省一段正则type="number" min="18" max="120" step="1"→ 数字、范围、加减按钮一次配齐type="tel" inputmode="numeric"→ 手机弹数字键盘,不纠结格式required→ 空着就拦截,比后端先吼一嗓子placeholder=" hint "→ 灰字提示,千万别当标签用,屏幕阅读器会忽略pattern="\d{6}"→ 6 位验证码,一行正则搞定autocomplete="one-time-code"→ iPhone 自动读短信,懒人福音readonly→ 只能看不能改,数据照样提交(跟disabled不一样)maxlength="11"→ 手机号多一位都敲不进去,手机端尤其爽
3. <textarea> 与 <select> 的小便签
textarea rows="4" cols="40" 只是“视觉面积”,真想锁死字数用 maxlength="200",再配个 currentLength/200 小字提示,用户心里有底。
select multiple 一开,ctrl 多选走起,记得把 name="hobbies[]" 写成数组格式,后端才好接。 size="5" 决定一次露几条,露太少就得拼命滚。
4. <button> 的三张脸
<button type="submit">保存</button>
<button type="button">辅助功能</button>
<button type="reset">清空</button>submit才是交卷;button默认啥也不干,全靠 JS;reset一按全表归零,慎用——用户填了十分钟被你一秒整没了,容易暴走。
5. <label> 的隐形福利
<label for="email">邮箱</label>
<input id="email" type="email" name="email">for 和 id 对上了,点文字就能聚焦输入框,手机用户秒懂。
别偷懒只写 <label>邮箱<input…,那样点字没反应,白白损失触控面积。
6. 一段能直接搬的“注册小卡片”
<form action="/register" method="post" enctype="multipart/form-data">
<label for="u">用户名</label>
<input id="u" name="username" type="text" required minlength="3" maxlength="15" autofocus>
<label for="e">邮箱</label>
<input id="e" name="email" type="email" placeholder="you@example.com" required>
<label for="p">密码</label>
<input id="p" name="pwd" type="password" required minlength="6" autocomplete="new-password">
<label for="age">年龄</label>
<input id="age" name="age" type="number" min="18" max="120" value="18">
<label for="avatar">头像</label>
<input id="avatar" name="avatar" type="file" accept="image/*">
<button type="submit">注册</button>
</form>把属性写全,前端就能先挡一半乱七八糟的数据;后端再补一刀校验,基本稳。
7. 最后一句话
表单属性不是“单词表”,而是“场景卡”。
哪里需要拦数据、给提示、做交互,就贴哪张。
贴对了,用户丝滑填完;贴错了,后台收到一堆 Heartbreak。
0
快来点个赞吧
发表评论
评论列表