【HTML5】——表单

HTML5的作用:

  1. 提供了更加强大的功能,方便开发
  2. 在移动端使用对应的input类型,当用户输入的时候,可以调取出对应的虚拟键盘,方便用户快速输入
  3. 相对于传统的表单类型提供了新的验证方式
目录

1.传统input表单类型
2.input新类型
3.表单新元素
4.表单新属性
5.表单新验证

1.传统input表单类型

text、password、submit、reset、button、radio、checkbox、file、hidden等

这里写图片描述

<input type="text">text
<br>
<input type="password">password
<br>
<input type="submit">submit
<br>
<input type="reset">reset
<br>
<input type="button" value="button">button
<br>
<input type="radio" name="sex" checked id="sexMan"><label for="sexMan">男</label>
<input type="radio" name="sex" id="sexWoman"><label for="sexWoman">女</label>radio
<br>
<input type="checkbox">checkbox
<br>
<input type="file">file
<br>
<input type="hidden">hidden
单选按钮

获取提交的内容:
提交男显示0,1代表女

<input type="submit" id="submit">
<input type="radio" name="sex" checked id="sexMan"><label for="sexMan"></label>
<input type="radio" name="sex" id="sexWoman"><label for="sexWoman"></label>

<script type="text/javascript">
    var submit = document.getElementById("submit"),
        sexMan = document.getElementById("sexMan"),
        sexWoman = document.getElementById("sexWoman");
    submit.onclick = function () {
        var sexType = 0;
        !sexMan.checked ? sexType = 1 : null;
        console.log(sexType);
    };
</script>

改变男/女,控制台输出改变的值

<input type="radio" value="男" name="sex" checked id="sexMan"><label for="sexMan"></label>
<input type="radio" value="女" name="sex" id="sexWoman"><label for="sexWoman"></label>
<script type="text/javascript">
    sexMan.onchange = sexWoman.onchange = function () {
        console.log(this.value);
    };
</script>
复选按钮

点击提交,输出对应内容:

<input type="checkbox" value="游泳" name="hobby" id="swim"><label for="swim">游泳</label>
<input type="checkbox" value="唱歌" name="hobby" id="sing"><label for="sing">唱歌</label>
<input type="checkbox" value="爬山" name="hobby" id="climb"><label for="climb">爬山</label>
<input type="checkbox" value="游戏" name="hobby" id="play"><label for="play">游戏</label>
<input type="checkbox" value="跳舞" name="hobby" id="dance"><label for="dance">跳舞</label>
<input type="checkbox" value="加班" name="hobby" id="code"><label for="code">加班</label>
<br>
<input type="submit" id="submit">

<script type="text/javascript">
    var submit = document.getElementById("submit"),
        hobbyList = document.getElementsByName("hobby");
    submit.onclick = function () {
        for (var i = 0; i < hobbyList.length; i++) {
            var curHobby = hobbyList[i];
            if (curHobby.checked) {
                console.log(curHobby.value);
            }
        }
    };
</script>
表单元素中的常用事件

PC端表单元素中的常用事件

click、change、focus、blur、keydown、keyup

移动端表单元素中的常用事件

在移动端没有keydown、keyup事件(部分手机识别),因为移动端使用的是虚拟键盘
移动端多了一个事件类型:input事件

2.input新类型

单选按钮(radio)

email类型
<input type="email" />

判断字符串中是否包含“@”符号,不能以“@”开头或结束

验证邮箱:

<input type="text" id="userEmailFir">
<br>
<input type="email" id="userEmailTwo">
<script type="text/javascript">
    //验证传统邮箱:
    ~function (pro) {
        function myTrim() {
            return this.replace(/^ +| +$/g, "");
        }

        pro.myTrim = myTrim;
    }(String.prototype);

    var userEmailFir = document.getElementById("userEmailFir"),
        userEmailTwo = document.getElementById("userEmailTwo");
    userEmailFir.onblur = function () {
        var val = this.value.myTrim();
        var reg = /^\w+((-\w+)|(\w+)|(\.\w+))*@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
        if (!reg.test(val)) {
            console.log("邮箱格式不正确");
        }
    };

    //验证H5邮箱:
    var userEmailFir = document.getElementById("userEmailFir"),
        userEmailTwo = document.getElementById("userEmailTwo");
    userEmailTwo.onblur = function () {
        var val = this.value.myTrim();
        if (!this.checkValidity()) {
            console.log("邮箱格式不正确");
        }
    };
</script>
搜索类型
<input type="search" />
URL类型
<input type="url" />

判断字符串中是否包含“http://”,以“http://”开始或结束都能通过

电话号码类型
<input type="tel" />

只在移动端有效

数字类型
<input type="number" />
  • 允许输入非数字内容,不允许提交(chrome不可以)
  • 设置min和max时,允许输入范围外的值,不允许提交

属性:

  1. min:设置数字的最小值
  2. max:设置数字的最大值
  3. step:设置步长,每次增加或减小的量值
  4. value:默认值
  5. disabled:不可编辑的
范围类型
<input type="range" />

属性:

  1. min:设置数字的最小值
  2. max:设置数字的最大值
  3. step:设置步长,每次增加或减小的量值
  4. value:当前值
颜色类型
<input type="color" />
日期类型
<input type="date"/>
周类型
<input type="week"/>
月类型
<input type="month"/>
颜色类型实例

需求:

  1. 3个滑动的条分别表示R、G、B三种颜色
  2. 范围都是0-255
  3. 将调整的颜色设置到div的背景颜色中

效果图:
这里写图片描述

代码如下:

<head>
    <meta charset="UTF-8">
    <title>input新类型</title>
    <style type="text/css">
        div {
            width: 150px;
            height: 150px;
            border: 1px solid black;
        }
    </style>
</head>
<body>
<div id="showColor"></div>
<br/>
红色:<input type="range" id="r" min="0" max="255" step="1" value="0"/><br/>
绿色:<input type="range" id="g" min="0" max="255" step="1" value="0"/><br/>
蓝色:<input type="range" id="b" min="0" max="255" step="1" value="0"/><br/>
<script type="text/javascript">
    var oInput = document.getElementsByTagName("input");
    var color = [];
    for (var i = 0; i < oInput.length; i++) {
        oInput[i].onchange = function () {
            color[0] = oInput[0].value;
            color[1] = oInput[1].value;
            color[2] = oInput[2].value;
            var oDiv = document.getElementById("showColor");
            oDiv.style.background = "rgb(" + color[0] + "," + color[1] + "," + color[2] + ")";
        };
    }
</script>
</head>
用户注册页面实例

效果图:
这里写图片描述

代码如下:

<body>
  <fieldset>
    <legend>用户注册页面</legend>
    <form>
        <table>
        <!--
        需求
        * 用户名
        * 密码
        * 确认密码
        * Email地址 - email
        * 年龄 - number 最小值为1,最大值为100
        * 手机号 - tel
        * 出生日期 - date
        * 个人主页 - url
        -->
            <tr>
                <td>用户名:</td>
                <td><input type="text" id="user"></td>
                <!-- 验证错误信息 -->
                <td><span id="userTip"></span></td>
            </tr>
            <tr>
                <td>密码:</td>
                <td><input type="password" id="pwd"></td>
                <td><span id="pwdTip"></span></td>
            </tr>
            <tr>
                <td>确认密码:</td>
                <td><input type="password" id="repwd"></td>
                <td><span id="repwdTip"></span></td>
            </tr>
            <tr>
                <td>Email:</td>
                <td><input type="email" id="email"></td>
                <td><span id="emailTip"></span></td>
            </tr>
            <tr>
                <td>年龄:</td>
                <td><input type="number" min="1" max="100" id="age"></td>
                <td><span id="ageTip"></span></td>
            </tr>
            <tr>
                <td>手机号:</td>
                <td><input type="tel" id="phone"></td>
                <td><span id="phoneTip"></span></td>
            </tr>
            <tr>
                <td>出生日期:</td>
                <td><input type="date" id="birth"></td>
                <td><span id="brithTip"></span></td>
            </tr>
            <tr>
                <td>个人主页</td>
                <td><input type="url" id="home"></td>
                <td><span id="homeTip"></span></td>
            </tr>
            <tr>
                <td></td>
                <td><input type="submit" value="注册"></td>
                <td></td>
            </tr>
        </table>
    </form>
  </fieldset>
 </body>
3.表单新元素
datalist标签

用法:

  1. 配合input元素使用
  2. 在input元素中定义list属性(值为datalist的id值)

好处:数据与结构的分离

<datalist id="cities">
    <option>北京市</option>
    <option>天津市</option>
    <option>南京市</option>
    <option>武汉市</option>
</datalist>
progress标签

作用:实现一个进度条
属性:

  1. max:设置进度条的最大值
  2. value:设置进度条当前的值
<progress max="100" value="0" id="progress"/>

实现动态进度条:

(function fn() {
    var progress = document.getElementById("progress");
    var max = progress.max;
    var value = progress.value;
    if (value == max) {
        clearTimeout(t);
    }
    value++;
    progress.value = value;
    t = setTimeout(fn, 100);
})();
meter标签

用法:与progress标签类似
作用:刻度
属性:

  1. min:设置最小值
  2. max:设置最大值
  3. value:当前值
  4. high:设置最大预警值
  5. low:设置最小预警值
<meter min="0" max="100" value="95" high="90" low="10"/>

实现刻度动态效果,代码如下:

(function fn() {
    var meter = document.getElementsByTagName("meter")[0];
    var max = meter.max;
    var value = meter.value;
    if (max == value) {
        clearTimeout(t);
    }
    value++;
    meter.value = value;
    t = setTimeout(fn, 100);
})();
output标签

输出框
在实际开发中很少使用
属性:for:与要输出的元素进行关联

4.表单新属性
placeholder属性

实现input输入框的默认提示信息,相比value属性值更好用

<input type="text" placeholder="请输入你的用户名:"/>

这里写图片描述

兼容IE:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title></title>
    <style type="text/css">
        * {
            margin: 0;
            padding: 0;
        }

        html, body {
            font-size: 14px;
            font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
            width: 100%;
            color: #000;
        }

        input {
            display: inline-block;
            outline: none;
        }

        .box {
            width: 200px;
            margin: 20px auto;
            position: relative;
        }

        .box input, .tip {
            width: 188px;
            border: 1px solid #ccc;
            height: 30px;
            line-height: 30px;
            padding: 0 5px;
        }

        .tip {
            display: none;
            position: absolute;
            color: #ccc;
            top: 0;
            left: 0;
            cursor: text;
        }

    </style>
</head>
<body>
<div class="box">
    <input type="email" id="userEmail" placeholder="请输入您的常用邮箱">
    <span class="tip" id="tipEmail">请输入您的常用邮箱</span>
</div>
<script type="text/javascript">
    if (navigator.userAgent.indexOf("MSIE") > -1) {
        var userEmail = document.getElementById("userEmail"),
            tipEmail = document.getElementById("tipEmail");
        userEmail.placeholder = "";
        tipEmail.style.display = "block";
        tipEmail.onclick = function () {
            userEmail.focus();
        };
        userEmail.onkeydown = userEmail.onkeydown = userEmail.onblur = userEmail.onfocus = function () {
            tipEmail.style.display = this.value.length === 0 ? "block" : "none";
        };
    }
</script>
</body>
</html>
multiple属性

作用:允许输入框输入多个值,多个值之间用逗号隔开
用法:只定义属性名即可,没有值

<input type="submit" multiple />
autofocus属性

作用:自动获取焦点
用法:只定义属性名即可,没有值

<input type="text" autofocus />
form属性

作用:允许表单元素定义在表单元素之外
值是相关联表单的id属性值

<input type="email" form="id" />
用户注册页面实例
<fieldset>
    <legend>用户注册页面</legend>
    <form action="">
        <table>
            <!--需求:
            使用placeholder属性,为每个元素增加默认提示
            使用autofocus属性,定义给id为user元素
            email允许输入多个
            -->
            <tr>
                <td>用户名:</td>
                <td><input type="text" id="user" placeholder="请输入用户名" autofocus></td>
                <!-- 验证错误信息 -->
                <td><span id="userTip"></span></td>
            </tr>
            <tr>
                <td>密码:</td>
                <td><input type="password" id="pwd" placeholder="请输入密码"></td>
                <td><span id="pwdTip"></span></td>
            </tr>
            <tr>
                <td>确认密码:</td>
                <td><input type="password" id="repwd" placeholder="请确认密码"></td>
                <td><span id="repwdTip"></span></td>
            </tr>
            <tr>
                <td>Email:</td>
                <td><input type="email" id="email" placeholder="请输入Email" multiple></td>
                <td><span id="emailTip"></span></td>
            </tr>
            <tr>
                <td>年龄:</td>
                <td><input type="number" min="1" max="100" id="age" placeholder="请输入年龄"></td>
                <td><span id="ageTip"></span></td>
            </tr>
            <tr>
                <td>手机号:</td>
                <td><input type="tel" id="phone" placeholder="请输入电话"></td>
                <td><span id="phoneTip"></span></td>
            </tr>
            <tr>
                <td>出生日期:</td>
                <td><input type="date" id="birth"></td>
                <td><span id="brithTip"></span></td>
            </tr>
            <tr>
                <td>个人主页</td>
                <td><input type="url" id="home" placeholder="请输入个人主页"></td>
                <td><span id="homeTip"></span></td>
            </tr>
            <tr>
                <td></td>
                <td><input type="submit" value="注册"></td>
                <td></td>
            </tr>
        </table>
    </form>
</fieldset>
5.表单新验证
验证属性——required

防止域为空时提交表单,不需要设置任何值
返回false:表示当前元素值为空;
返回true:表示当前元素值不为空

<input type="text" required />
验证属性——pattern

实现元素的验证,支持使用正则表达式定制验证规则
此处正则表达式不能验证为空(使用required),不能添加/ /

<input type="tel" pattern="^[0-9]{6-8}$" />
验证属性——min、max

验证最小值和最大值
只和number类型的属性配合使用

验证属性——minlength、maxlength

验证最小长度和最大长度
该属性不是HTML5属性

验证属性——validity

HTML5提供表单验证的接口
通过该属性可以得到ValidityState对象,该对象提供一系列的有效状态,可用于表单验证
获取ValidityState对象:语法:

指定元素.validity

作用:替换之前的正则表达式

有效状态

valid:返回Boolean,表示验证是否通过
    true:表示验证通过
    false:表示验证失败

valueMissing:表示值是否为空
    true:表示元素值为空(错误)
    false:表示元素值不为空(正确)
    该状态配合require使用

typeMismatch:表示元素类型是否匹配
    true:表示元素类型不匹配
    false:表示元素类型匹配
    该状态配合email、url、number

patternMismatch:表示正则表达式是否匹配,如果输入内容与所设置模式不匹配,那么这个状态就是true
    true:表示正则表达式不匹配
    false:表示正则表达式匹配
    该状态配合pattern属性

tooLong:表示元素内容是否过长
    true:表示元素内容过长
    false:表示元素内容不长
    该状态配合maxlength属性
    tooLong可能不会出现(验证完整性)

rangeUnderflow:表示元素值是否小于min的值
    true:表示元素值小于min的值
    false:表示元素值不小于min的值
    该状态配合min属性

stepMismatch:表示元素值与step值是否符合
    true:表示元素值与step值不符合
    false:表示元素值与step值符合
    该状态配合step属性

customError:自定义错误
    setCustomValidity(自定义错误信息);
    一旦调用该方法,默认都是错的,上述所有的有效状态返回错误值,配合setCustomValidity()方法
    验证正确时,调用该方法,将错误信息置为空
    

HTML5的自定义错误提示函数实例
<body>
<form>
    <input type="text" required id="i"/>
    <input type="submit" onclick="formValidate()"/>
</form>
<script type="text/javascript">
    function formValidate() {
        var i = document.getElementById("i");
        if (i.validity.valueMissing) {
            i.setCustomValidity("元素不能为空");
        } else if (i.validity.customError) {
            //表示调用setCustomValidity()方法
            i.setCustomValidity("");
        }
    }
</script>
</body>
HTML5的有效状态实例
<body>
<fieldset>
    <legend>HTML5的有效状态</legend>
    <form>
        <table>
            <tr>
                <td>用户名:</td>
                <td><input onclick="formValidate();" type="text" id="i1" maxlength="5" pattern="^[0-9]{5}$"/></td>
            </tr>
            <tr>
                <td>Email:</td>
                <td><input type="email" id="e" onclick="formValidate();"/></td>
                <td><span id="emailTip"></span></td>
            </tr>
            <tr>
                <td>年龄:</td>
                <td><input type="number" id="n" min="0" max="10" step="2"/></td>
                <td><span id="ageTip"></span></td>
            </tr>
        </table>
    </form>
</fieldset>
<script type="text/javascript">
    //    使用HTML5中的验证属性时
    //required为input元素绑定事件,底层具有阻止事件冒泡
    //为form表单绑定onsubmit事件,导致失效
    function formValidate() {
        //获取input元素
        var value = document.getElementById("i1").value;
        //判断input元素知否为空
        //顺序不能错
        if (value.validity.valid) {
            console.log("input不为空");
        } else if (value.validity.valueMissing) {
            console.log("input为空");
        } else if (value.validity.patternMismatch) {
            //表示正则不匹配
            console.log("正则不匹配");
        } else if (value.validity.tooLong) {
            console.log("输入内容过长");
        }
        var e = document.getElementById("e");
        if (e.validity.typeMismatch) {
            //表示类型不匹配
            console.log("email输入有误");
        }
        var n = document.getElementById("n");
        if (n.validity.rangeUnderflow) {
            //表示值小于min值
            console.log("值过小");
        } else if (n.validity.stepMismatch) {
            console.log("step不对");
        }
        return false;
    }
</script>
</body>
用户注册页面
<fieldset>
    <legend>用户注册页面</legend>
    <form action="">
        <table>
            <!--需求:
            表单中所有元素不能为空
            用户名:必须英文+数字,长度在6-12之间
            密码:必须是英文,6-8之间
            手机号:开始为1,后面为数字,13位
            -->
            <tr>
                <td>用户名:</td>
                <td><input type="text" required minlength="6" maxlength="12" pattern="^[a-zA-Z0-9]+$" autofocus /></td>
                <!-- 验证错误信息 -->
                <td><span id="userTip"></span></td>
            </tr>
            <tr>
                <td>密码:</td>
                <td><input type="password" id="pwd" required placeholder="请输入密码" minlength="6" maxlength="8" pattern="^[a-zA-Z]+$" /></td>
                <td><span id="pwdTip"></span></td>
            </tr>
            <tr>
                <td>确认密码:</td>
                <td><input type="password" id="repwd" required placeholder="请确认密码" minlength="6" maxlength="8" pattern="^[a-zA-Z]+$" /></td>
                <td><span id="repwdTip"></span></td>
            </tr>
            <tr>
                <td>Email:</td>
                <td><input type="email" id="email" required placeholder="请输入Email" multiple></td>
                <td><span id="emailTip"></span></td>
            </tr>
            <tr>
                <td>年龄:</td>
                <td><input type="number" required min="1" max="100" id="age" placeholder="请输入年龄"></td>
                <td><span id="ageTip"></span></td>
            </tr>
            <tr>
                <td>手机号:</td>
                <td><input type="tel" required pattern="^1[0-9]{10}$" /></td>
                <td><span id="phoneTip"></span></td>
            </tr>
            <tr>
                <td>出生日期:</td>
                <td><input type="date" required id="birth"></td>
                <td><span id="brithTip"></span></td>
            </tr>
            <tr>
                <td>个人主页</td>
                <td><input type="url" required id="home" placeholder="请输入个人主页"></td>
                <td><span id="homeTip"></span></td>
            </tr>
            <tr>
                <td></td>
                <td><input type="submit" value="注册"></td>
                <td></td>
            </tr>
        </table>
    </form>
</fieldset>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值