参考原文:01-HTML5详解.md
HTML5中一个显著的改进属性就是表单,增加可读性和丰富其内容,方便操作。
1.表单类型
- 最外层标签:<form action="">包裹所有input,内容为提交的地址,下述input则必须有name值
-
次外层:<fieldset>,对表单中的相关元素进行分组
-
内层:<legend>表单标题</legend>
-
内层:<label for="">,浏览器就会自动将焦点转到和标签相关的表单控件上。
-
以下都包含在<label for="">内为最内层标签:标签
标签 | 含义 |
email: <input type="email" name="email" required><!-- required必填 --> |
邮件 |
color: <input type="color" name="color"></label> |
拾色器 |
url: <input type="url" name='url'> |
网址 |
number: <input type="number" step="3" name="number"> |
变化框 |
range: <input type="range" name="range" value="100"> |
滑动条 |
search: <input type="search" name="search"> |
搜索框 |
tel: <input type="tel" name="tel"> |
电话 |
time: <input type="time" name="time"> |
时间(可选) |
date: <input type="date" name="date"> |
日期(可选) |
datetime: <input type="datetime"> |
日期时间 (手输) |
week: <input type="week" name="week"> |
星期 |
month: <input type="month" name="month"> |
月份 |
datetime-local: <input type="datetime-local" name="datetime-local"> |
本地具体时间(可选) |
效果如下:
2.表单标签datalist
<input type="text" list="Data">
<datalist id="Data"><!-- input里的list和datalist绑定,同时,代码有提示功能 -->
<option>本科</option>
<option>研究生</option>
<option>博士生</option>
</datalist>
效果如下:
3.表单属性
- 提示文字和自动获取焦点
<input type="text" placeholder="例如:hyo" autofocus name="userName" autocomplete="on" required/>
placeholder 占位符(提示文字)
autofocus 自动获取焦点
autocomplete 自动完成(填充的)。on 开启(默认),off 取消。用于表单元素,也可用于表单自身(on/off)
- 自定义正则,验证表单
<input type="tel" pattern="1\d{10}"/>
上述代码一般用于手机号码验证,1表示要求数字,d{10}可填10+1个数
- 上传文件
<input type="file" name="file" multiple/>
效果如下:
补充:
- input不是盒子,设置css时需要设置为block;
-
label 元素不会向用户呈现任何特殊效果。不过,它为鼠标用户改进了可用性。如果在 label 元素内点击文本,就会触发此控件。就是说,当用户选择该标签时,浏览器就会自动将焦点转到和标签相关的表单控件上
-
<label> 标签的 for 属性应当与相关元素的 id 属性相同。
4.表单事件
var txt1 = document.getElementById('txt1');
var txt2 = document.getElementById('txt2');
var num = 0;
txt1.oninput = function () { //用户输入时触发
num++; //用户每输入一次,num自动加 1
//将统计数显示在txt2中
txt2.value = num;
}
txt1.oninvalid = function () { //验证不通过时触发
this.setCustomValidity('亲,请输入正确哦'); //设置验证不通过时的提示文字
}
效果如下: