【HTML5】HTML5 高级程序设计 学习笔记Froms API

Froms API

写在前面:
兼容性:多层 自动降级
有时候我会用库
新的表单特性和函数:浏览器不支持的时候会直接忽略。


1、新表单特性和函数

placeholder:向用户显示描述性说明或提示信息,如:。

autocomplete:用来保护敏感用户数据,避免本地浏览器进行存储 ,主要有 on(字段值无需保护)、off(字段值需要保护)、unspecified三种行为。如:

autofocus:指定某个表单元素获得输入焦点

list和datalist:组合使用这两个特性可以为输入型控件构造一张选值列表,使用方法如下:
(1)创建id值唯一的datalist元素,可以在文档任意位置插入;
(2)添加若干option元素,如:

<datalist id="contactList">
    <option value="2@xx.com" label="Racer">
    <option value="3@xx.com" label="Perter">
</datalist>

(3)将input的list特性值设置为datalist的id值


min和max:主要用于range元素

step:指定输入值递增或递减的粒度。

valueAsNumber函数:完成控件值类型在文本与数值间的相互转换

required:指定表单元素为必填

2、表单验证

valueMissing

目的:确保表单控件中的值已填写

用法:设置控件的required为true

typeMismatch

目的:保证控件值与预期类型相匹配

用法:指定 表单控件的type特性值

patterMismatch

目的:根据控件设置的格式规则验证输入是否为有效格式

用法:指定控件的pattern特性,并赋予适当的匹配规则

tooLong

目的:避免值包含过多字符

用法:设定控件的maxLength特性

rangeUnderFlow

目的:限制数值型控件的最小值

用法:设置控件的min特性,并赋值

rangeOverflow

目的:限制数值型控件的最大值

用法:设置控件的max特性,并赋值

stepMismatch

目的:确保输入值符合min、max及step设置

用法:设置控件的step特性,并赋值

customError

目的:处理代码及计算产生的错误

用法:调用setCustomValidity((message)将控件置于customError状态

注意:还可以通过表单控件来访问ValidityState对象,如var check = documenet.myForm.myInput.validity;然后调用check.valid。

3、验证反馈

在HTML5中,如果开发人员想把错误消息反馈给用户,可以使用invalid事件。

function invalidHandler(evt){
    var validity = evt.srcElement.valididy;
    if(validity.valueMissing){
        //提示用户必填项中没有填值
    }
    //检测其他约束条件
    //如果不希望浏览器提供默认的验证反馈,可以取消事件
    evt.preventDefault();
}


//注册 invalid事件的监听器__halt_compiler

myField.addEventListener("invalid",invalidHandler,false)

还可以通过设置noValidate特性来关闭验证。
formnovalidate - 重写表单的 novalidate 属性

4、代码Demo

完整案例:

4.1-注册页面:

<!DOCTYPE html>

<html>
<head>
<title>Tahoe 216</title>
    <meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<link rel="stylesheet" href = "html5.css">

<style type="text/css">

label {
    text-align: right;
    width: 90px;
    float: left;
}

input {
    margin-top: 0px;
    padding-top: 0px;
}

fieldset {
    margin-top: 5px;
}

#confidenceDisplay {
    vertical-align: top;
}
</style>

<script>
    function setConfidence(newVal) {
        document.getElementById("confidenceDisplay").innerHTML = newVal + '%';
    }

    function invalidHandler(evt) {
        // find the label for this form control
        var label = evt.srcElement.parentElement.getElementsByTagName("label")[0];

        // set the label's text color to red
        label.style.color = 'red';

        // stop the event from propagating higher
        evt.stopPropagation();

        // stop the browser's default handling of the validation error
        evt.preventDefault();
    }
    function loadDemo() {
       // register an event handler on the form to
       // handle all invalid control notifications
       document.register.addEventListener("invalid", invalidHandler, true);
    }

    window.addEventListener("load", loadDemo, false);

</script>

</head>

<body>
    <div id="container">
    <header>
        <h1>Tahoe 216</h1>
        <h3 align="center">3 Days, 216-Miles, One Crazy Runner's High</h3>
        <h2>&nbsp;</h2>
        <h4>Live  Results Now!</h4>
    </header>

    <nav>
        <h2>Links</h2>
        <a href="index.html" title="Home">Home</a>
        <a href="signup.html" title="Are you crazy enough?">Sign Up</a>
        <a href="about.html" title="Learn more about the T216">About the Race</a>
    </nav>

    <section>
      <article>
        <h2>Sign Up Today</h2>
        <p><strong>Race fee</strong>: $216 </p>
        <p>Make check payable to the Happy Trails Running Club</p>
        <p><strong>Note</strong>: We  recommend that you seek your doctor's and family's approval before you sign up. Race fees are not refundable. </p>
        <form name="register">
          <p><label for="runnername">Runner:</label>
             <input id="runnername"name="runnername" type="text"
                    placeholder="First and last name" required></p>
          <p><label for="phone">Tel #:</label>
             <input id="phone" name="phone" type="tel"
                    placeholder="(xxx) xxx-xxx"></p>
          <p><label for="emailaddress">E-mail:</label>
             <input id="emailaddress" name="emailaddress" type="email"
                    placeholder="For confirmation only"></p>
          <p><label for="dob">DOB:</label>
             <input id="dob" name="dob" type="date"
                    placeholder="MM/DD/YYYY"></p>
          <fieldset>
            <legend>T-shirt Size: </legend>
            <p><input id="small" type="radio" name="tshirt" value="small">
               <label for="small">Small</label></p>
            <p><input id="medium" type="radio" name="tshirt" value="medium">
               <label for="medium">Medium</label></p>
            <p><input id="large" type="radio" name="tshirt" value="large">
               <label for="large">Large</label></p>
            <p><label for="style">Shirt style:</label>
               <input id="style" name="style" type="text" list="stylelist" title="Years of participation"></p>
            <datalist id="stylelist">
             <option value="White" label="1st Year">
             <option value="Gray" label="2nd - 4th Year">
             <option value="Navy" label="Veteran (5+ Years)">
            </datalist>
          </fieldset>
         <fieldset>
            <legend>Expectations:</legend>
            <p>
            <label for="confidence">Confidence:</label>
            <input id="confidence" name="level" type="range"
                   onchange="setConfidence(this.value)"
                   min="0" max="100" step="5" value="0">
            <span id="confidenceDisplay">0%</span></p>
            <p><label for="notes">Notes:</label>
               <textarea id="notes" name="notes" maxLength="140"></textarea></p>
         </fieldset>

         <p><input type="submit" name="register" value="Register"></p>
        </form>
      </article>
    </section>

    <aside>
      <h2>Sponsors</h2>
      <p align="center">Happy Trails Running Club</p>
     <p align="center"><img src="happy-trails-rc.gif" alt="Happy Trails Running Club" width="149" height="207"></p>
    </aside>

    <footer>
        <p>Powered by HTML5</p>
    </footer>

    </div>
</body>
</html>

这里写图片描述
在Chrome浏览器显示效果

4.2-密码是否一致重写验证:

<!DOCTYPE html>

<html>
<head>
<title>Password Match</title>

<script>
    function checkPasswords() {
        var pass1 = document.getElementById("password1");
        var pass2 = document.getElementById("password2");

        if (pass1.value != pass2.value)
            pass1.setCustomValidity("Your passwords do not match. Please recheck that your new "+"password is entered identically in the two fields.");
        else
            pass1.setCustomValidity("");
    }


    function invalidHandler(evt) {
        // set the label's text color to red
        evt.srcElement.style.background = 'red';

        // stop the event from propagating higher
        evt.stopPropagation();

        // stop the browser's default handling of the validation error
        evt.preventDefault();
    }

    function loadDemo() {
       // register an event handler on the form to
       // handle all invalid control notifications
       document.passwordChange.addEventListener("invalid", invalidHandler, true);
    }

    window.addEventListener("load", loadDemo, false);
</script>

</head>

<body>
<form name="passwordChange">
    <p><label for="password1">New Password:</label>
    <input type="password" id="password1" onchange="checkPasswords()"></p>
    <p><label for="password2">Confirm Password:</label>
    <input type="password" id="password2" onchange="checkPasswords()"></p>
</form>
<button onclick="document.passwordChange.password1.checkValidity()">Check Validity</button>

</body>
</html>

在Chrome显示效果:
这里写图片描述
在FireFox显示效果:
这里写图片描述

4.3-输入过滤:

<!DOCTYPE html>

<html>
<head>
<title>Pattern List</title>

<!--
This demo does not yet work in any browsers at the time of publication.
It was planned to be an additional Practical Extra called "Natural (List) Selection".

It was meant to show how you can use patterns to restrict the values in a datalist
live so that as the user types, the datalist options are filtered. Datalists are only
supported in Opera at the moment, and this demo works there. Sort of. Unfortunately,
when the pattern is applied, the visuals of the list don't actually reflect that
until the next keypress. So it always lags behind by one key. I tried everything I
could to force it to refresh the list immediately, but to no avail. Maybe this will
work when other browsers like Chrome and Safari add their datalist support.
-->

<script>
    function filterList(field) {
        // get the current value from the field
        var currVal = field.value;

        // escape any regular expression characters from the entered text
        currVal = currVal.replace(/([.*+?|(){}[\]\\])/ig, "\\$1");

        field.pattern = currVal + ".*";
    }

</script>

</head>

<body>

<form name="listForm">
    <p><label for="patternList">Select from the list:</label>
    <input type="text" id="patternChoice" list="fullList" onkeydown="filterList(this)"></p><!-- this 表示是输入框-->
    <datalist id="fullList">
        <option value="one">
        <option value="two">
        <option value="three">
        <option value="four">
        <option value="five">
        <option value="six">
        <option value="seven">
        <option value="eight">
        <option value="nine">
        <option value="ten">
    </datalist>
    <span>Type in the field to filter the options.</span>
</form>
</body>
</html>

这里写图片描述

Book Description HTML5 is here, and with it, rich Internet applications (RIAs) take on a power, ease, scalability, and responsiveness that neither Ajax nor Comet could ever achieve. With this book, developers will learn how to use the latest cutting-edge web technology—available in the most recent versions of modern browsers—to build real-time web applications with unparalleled functionality, speed, and responsiveness. The HTML5 specification represents the next evolution—or rather, a revolution—of web communications required to build real-time applications. WebSockets and server-sent events provide not only a standard against which real-time web applications can be built, but also a socket, native to the browser, that facilitates network programming from the browser with efficient bidirectional (full-duplex) communication over a single connection. * Explains how you can create real-time HTML5 applications that tap the full potential of modern browsers * Provides practical, real-world examples of HTML5 features in action * Shows which HTML5 features are supported in current browsers and platforms What you’ll learn * How the HTML5 specification has evolved * How to design, develop, and run cutting-edge real-time web applications using new HTML5 features like WebSockets, server-sent events, cross-document messaging, geo location, storage, canvas, and video * Which features are available in browsers today and how you can run your applications in older browsers that do not support HTML5 features * How to use client-side APIs to communicate directly with back-end systems such as messaging systems, JMS brokers, XMPP servers, and online services such as Google Wave Who is this book for? This book is for developers who want to use the latest cutting-edge technology available in current browsers; developers who want to create dynamic, data-driven web applications; and developers who want to know which HTML5 features are supported in current browsers. About the Author Peter Lubbers is the Director of Documentation and Training at Kaazing Corporation, where he oversees all aspects of documentation and training. Peter also teaches a three-day HTML5 training course for Skills Matter. Prior to joining Kaazing, Peter worked as an information architect at Oracle, where he wrote many books, including the award-winning Oracle Application Server Portal Configuration Guide. At Oracle, Peter also developed documentation automation solutions and two of his inventions are patented. A native of the Netherlands, Peter served as a Special Forces commando in the Royal Dutch Green Berets. Peter lives on the edge of the Tahoe National Forest and in his spare time, he loves to run in the Sierra Nevada foothills and around Lake Tahoe (preferably in one go!). Brian Albers is the VP of development at Kaazing. Brian has over 13 years of experience in the field of User Interface technologies. Prior to joining Kaazing, Brian worked as Senior Development Manager at Oracle, where he led the planning and designing of the next generation of Oracle's UI technology—an effort publicly known as ADF Faces. During his 10 year tenure at Oracle, Brian worked primarily on mixing cutting-edge technology with large enterprise demands (internationalization, accessibility, scalability). He proposed the open source donation of ADF Faces, which ultimately became the Apache MyFaces Trinidad project. Brian also led a cross-team effort to develop a DHTML rich client and a mobile client presentation layer for Oracle's Project Fusion. Brian received a BS degree in Computer Science from the University of Texas, Austin, and a BA degree in Plan II Honors from the University of Texas, Austin. Frank Salim is a polyglot programmer with a keen interest in making life easier for his fellow coders. Frank leads WebSocket development at Kaazing. He is an open source advocate and a committer in several open source projects. Ric Smith is director of Oracle’s Fusion Middleware E20 Architect Team. Formerly, he led business and product strategy at Kaazing. Ric has also held various roles in product management, consulting, and software engineering. In addition, Ric is a frequent speaker at international events and has written articles featured in leading industry publications such as Java Developer's Journal and AJAX World Magazine.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值