28 HTML5 features, tips and techniques you must know

Source: Internet
Author: User
Tags button type jquery library

Translation-28 HTML5 features, tips and techniques you must know

by Zhangxinxu from http://www.zhangxinxu.com
This address: http://www.zhangxinxu.com/wordpress/?p=1058

Original address: http://net...html5-features-tips-and-techniques.../
Original Jeffrey
Translation small: Zhang Xin Xu

ZXX: The following is the translation of the full text, in accordance with the principles of vivid language and localization, the content is edited

Note: Several times a week, this list updates some new tricks, and ultimately, this article becomes a super-useful resource.
ZXX: Ugly Words said in front, I do not have the time to update, so, even to your daughter married day, this article is still 28 items

The development of the front-end is so rapid, one is not careful, warrior you may be far away in the back. If you don't want to be overwhelmed by the HTML5 change/update, you can use the content of this article as a warm-up course you must know.

First, the new DOCTYPE//zxx: "DOCTYPE" Chinese means "document type"

Still in the trouble of using the XHTML document type that can't remember living?

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en"       

If so, why is it still in use? Replace it with the new HTML5 document type. You'll live longer--as Douglas Quaid said.

<! DOCTYPE html>  

I just figured out that for HTML5 to get a code like this, you might be skeptical about the code being unreliable. Don't worry, this is now possible, only the old browser needs a specific DOCTYPE (document type). If the browser does not know DOCTYPE, it is easy to render the included tags in standard mode. So, sister, you boldly forward, to be cautious forget all about, to embrace the new HTML5 document type.

Ii. graphical elements (the figure Element)

Take a look at the following markup to add to the image:

<p>image of Mars. </P>     

Text wrapped in the P tag, and the IMG tag each line of its way, it is difficult to think that this is the title. The HTML5 <figure> is corrected by adopting elements. When the <figcaption> combination of elements is used, we can semantically think of this as the caption corresponding to the picture.

<figure>        <figcaption>        <p>this are An image of something interesting. </p>    </figcaption></figure>
Iii. redefinition of <small>

Not long ago, <small> elements were used to create a related subtitle near the logo. This is a very useful expression element, but, for now, this usage may not be correct. The <small> element has been redefined to mean the small print and thus more usable. Imagine the copyright status at the bottom of your site, which <small> can be properly wrapped according to the new HTML5 definition of this element.

The small element refers to the "small print".

Iv. scripts (scripts) and links (link) do not require type

You may still be adding the Type property to the link and script tags.

<link rel= "stylesheet" href= "Path/to/stylesheet.css" type= "text/css"/><script type= "Text/javascript" src= " Path/to/script.js "></script>

This is already an old lily, not a necessity. This means that the labels each point to the style sheet and script. Therefore, we can kill the type attribute together.

<link rel= "stylesheet" href= "Path/to/stylesheet.css"/><script src= "Path/to/script.js" ></script>
Five, quotation marks or not quotation marks ... This is really a problem. Remember, HTML5 is not XHTML, and if you don't, you don't have to have to enclose your attributes in quotation marks, and it's not necessary to close the elements. In other words, as long as you feel comfortable, there is no right or wrong point. That's the way it is for me.

You have to make your own decisions about that. If you prefer structured documents, even if the sky falls down, enclose the quotation marks firmly in your arms.

Vi. content can be edited

The latest browser has a great new property that can be applied to the element, called contenteditable . As implies is to allow the user to edit any text contained in the content of the element, including child elements. There are a number of similar uses, like a simple to-do list application, that can take advantage of its local storage.

<ul contenteditable= "true" >    <li> Mourning Hong Kong compatriots </li>    <li> Shenzhen 30 Anniversary </li>    < Li> Yichun air crash </li></ul>

Or, based on some of the techniques we've learned earlier, we can write it:

<ul contenteditable=true>

You can simply click here: HTML5 Content Editable Demo

Seven, email input (Inputs)

If we apply the type attribute named "email" to the form input box, we can command the browser to allow only strings that conform to a valid e-mail address structure. Yes, the built-in form verification is coming, for some obvious reasons, we can't 100% rely on built-in verification, older browsers do not recognize the "email" type, they will simply fall back to the normal text box.

<form action= "" method= "get" >    <label for= "email" > Email: </label><input id= "email" name= "email" type= "Email"/>     <button type= "Submit" > OK </button></form>

You can really click here: HTML5 email built-in verification demo

ZXX: After my small test, seemingly only in the Chrome browser has the effect (XP system), when the input is not a legitimate mailbox format, click the "OK" button is not responding; When entered as a legitimate mailbox, click the "OK" button will not submit the Refresh page.

For now, we cannot rely on browser authentication, and client/server authentication is required.

It should also be noted that all current browsers are a bit unreliable when it comes to which elements and attributes are supported and unsupported. For example, Opera seems to support email validation, but only when the Name property is specified. Moreover, it does not support placeholder attributes, which we will learn later. The bottom line is not dependent on this form of validation ... But you can still use it!

Eight, placeholder (placeholders)//zxx: Here the content is not literal translation, has the deletion

Placeholders what do you mean, the text box/text field space will have a text hint by default, when you get the focus, the hint text disappears; If the content is empty when the focus is lost, the prompt text appears again. As shown in the following:

Some of the suggestive text shown in these form controls is a placeholder. In the past, we need to use a bit of JavaScript code to implement placeholder effects, such as the one shown in my Previous text box/field text prompt to automatically show hidden jquery widgets. Of course, you need to set an initial default value, and then determine the value of the text box based on what you have entered. If you use the placeholder (placeholders) attribute, everything is easy.

According to my test, currently only WebKit core browsers support placeholders properties, such as CHROME5,SAFARI4, the results are as follows:

You can really click here: HTML5 placeholder Demo

Ix. Local Storage (locally Storage) thanks to local storage (informal HTML5, for the purpose of convenience), we can let the advanced browser remember our edited content, even if the browser is turned off or the page is refreshed.

ZXX: The original video is shown by default YouTube video, not FQ to see, so, here to show the video from another site. Suggest full-screen viewing to see HTML and JavaScript code

ZXX: According to the video content, I made a demo of my own, about local storage.

You can really click here: HTML5 Local Storage Demo

The IE8 browser already supports local storage, as follows:

While it is clear that all browsers are not supported, we can expect this to work in Safari 4 and Firefox 3.5 when we Explorer8 the Internet. Please note that in order to compensate for the old browser will not recognize the local storage, you should first test to determine whether Window.localstorage exists.

Ten, the semantic header and the footer

Those days of the past:

<div id= "header" >...</div><div id= "Footer" >...</div>

Div, it's natural, there's no semantic structure--even after the ID is applied. Now, with HTML5, we can use


 
 

It's perfect for items where you have multiple headers and footers.

Try not to confuse the "header" and "footer" elements. They only refer to their containers. Therefore, it makes sense to put the meta information inside the footer element at the bottom of the blog, for example. This also applies to the header.

Xi. more HTML5 form features (more HTML5 form Features)

Learn more useful HTML5 form features from the video below://zxx:toutube video, need to FQ

12. IE and HTML5 (Internet Explorer and HTML5)

Unfortunately, the annoying IE browser needs a little bit of surgery to understand the new HTML5 element.

All elements, by default, have an inline display

To ensure that all new HTML5 elements are correctly rendered at block level elements, it is necessary to define them as follows:

Header, footer, article, section, Nav, menu, hgroup {      display:block;  }  

Unfortunately, IE still ignores these styles because it doesn't know where these tags come from, like header elements. Fortunately, there is a simple workaround:

Document.createelement ("article");d ocument.createelement ("footer");d ocument.createelement ("header"); Document.createelement ("Hgroup");d ocument.createelement ("Nav");d ocument.createelement ("menu");

Oddly enough, this code seems to trigger IE browser. To make it easier to apply this to each new application, Remichap (Remy Sharp) created a script, often referred to as HTML5 Shiv. The script also fixes some display problems.

<!--[if Ie]><script src= "Http://html5shim.googlecode.com/svn/trunk/html5.js" ></script><! [endif]-->
13. Information on a part of the document (Hgroup) Imagine that, in the title of my site, I have the name of my site, followed immediately by a subtitle. While we can use a
14. Necessary attributes (Required Attribute)

The form allows the new necessary properties to specify whether special input is required. Depending on your code preferences, you can declare this property in one of the two ways below.

<input type= "text" name= "Someinput" required>  

Or, use a more structured approach:

Both of these methods are OK. With this code, and the browser supports this property, if the "someinput" text box is blank, the form will not be submitted. Here's a simple example, we'll also add placeholder properties because there's no reason not to do so.

<form action= "" method= "get" >    <label for= "name" > name:</label>    <input id= "name" Name= " Name "type=" text "placeholder=" Zhangxinxu "required=" required "/>     <button type=" Submit "> Submit </button ></form>

You can fiercely click here: HTML5 Required Properties Demo

If the contents of input are blank, the text box will be highlighted when the form is submitted. //zxx: Looks like a little bit of a small effect in chrome

XV, Autofocus properties

Similarly, HTML5 's solution eliminates the need for JavaScript. If a particular input should be "selected", or focused, by default, we can now take advantage of the auto-get focus property.

<input type= "text" name= "Someinput" placeholder= "Zhangxinxu" required autofocus>

Interestingly, although I am personally more inclined to like the XHTML method (in quotation marks, etc.), writing "Autofocus=autofocus" makes people feel a bit strange. Therefore, we will stick to the method of using a single keyword.

16. Audio Support

We no longer have to rely on third-party plug-in areas to render audio. HTML5 provides <audio> elements, well, at least, eventually, we won't have to worry about these plugins. For now, only the most recent browsers offer HTML5 audio support. At this time, it is still a good practice to provide some form of backward compatibility.

<audio autoplay= "AutoPlay" controls= "Controls" >    <source src= "File.ogg"/> <source src=    " File.mp3 "/>    <a href=" File.mp3 ">download this file.</a></audio>

Mozilla and WebKit are not yet fully involved, when it comes to audio formats, Firefox will want to see an. ogg file while the WebKit browser supports the. mp3 extension. This means that, at least for now, you should create two versions of audio.

When Safari loads the page, it does not recognize the. ogg format and will skip it and move to the MP3 version, so. Please note ie, as usual, does not support these formats, Opera 10 and the following versions can only use. wav files.

17. Video Support

<audio>similar to elements, there are also video! in the new browser In fact, just recently, YouTube announced the new HTML5 video embedding, of course, to support this feature browser. Because the HTML5 specification does not specify a specific video codec, it is left to the browser to decide. While Safari and internet Explorer9 can expect to support videos in the H. s format (where Flash players can play), Firefox and Opera are sticking to the open source Theora and Vorbis formats. Therefore, when displaying HTML5 videos, you must provide both formats.

<video controls preload>    <source src= "COHAGENPHONECALL.OGV" type= "Video/ogg; codecs= ' Vorbis, Theora '"/ >    <source src= "Cohagenphonecall.mp4" type= "VIDEO/MP4; ' codecs= ' avc1.42e01e, mp4a.40.2 ' "/>    <p> Your browser are old. <a href=" Cohagenphonecall.mp4 "> Download this video instead.</a> </p></video>
Either "OGG" format or "Mp4″ format video Chrome browser can encode correctly

There is one more thing to note:

    1. We don't technically need to set the Type property, but if we don't, the browser has to look for the type on its own. Save some bandwidth, or declare it yourself.
    2. Not all browsers understand HTML5 video. Below the resource element, we can provide a download link, or a flash version of the embedded video instead. It depends on you.
    3. The controls and preload properties are mentioned below.
    4. There are ways to make all browsers support the video tag, see the article "Let all browsers support HTML5 video tag" in front of me.
18, video Pre-load (preload Videos)

Preload properties are not exactly what you want to look like, though, you should first decide whether you want to pre-install the video in the browser. Is it necessary? Well, maybe. If a visitor visits a page that specifically shows a video, you must preload the video to save the visitor a part of the time waiting. The movie can be preloaded by setting preload= "preload" or simply adding preload. I prefer the latter solution, which has a little bit of superfluous stuff.

<video preload>
19. Display Control bar

If you have used each of the above mentioned technical points, you may have noticed that using the above code, the video only shows a picture, there is no control bar. In order to render the playback control bar, we must specify the controls property within the video element.

<video preload controls>

Please note that the progress bars rendered by different browsers are not the same.

20. Regular Expressions

How often do you find yourself hastily writing some regular expressions to validate a specific text. Thanks to the new pattern property, we can insert a regular expression directly at the label.

<form action= "" method= "get" >    <label for= "username" > name:</label>    <input id= "username" Name= "username" type= "text" placeholder= "4-10 English letters" pattern= "[a-za-z]{4,10}" required= "required" autofocus/>     <button type= "Submit" > Submit </button></form>

If you are familiar with regular expressions, it should be clear [A-Za-z]{4,10} that you accept 4-10-bit case-insensitive English letters. If the browser supports the Pattern property, the text box is highlighted when the form is submitted, if the contents of the text box do not conform to its regular expression. As shown in.

You can really click here: HTML5 Regular Expression Demo

ZXX: I have a small test, it seems that currently only available under Chrome (Win system)

Notice that we've started to combine these great properties.

If you are vague about the concept of regular expressions, you can see here.

21. Attribute Support Detection

If we do not have a way to detect whether the browser supports these properties, these cannot be called good properties. Well, good point of view, in fact we have several methods, here we discuss 2. The first is the use of a good Modernizr library, or we can create and analyze these elements to determine the capabilities of the browser. For example, in our previous example, if we were to determine whether the browser could use the pattern attribute, we could add a small piece of JavaScript to our page:

Alert (' Pattern ' in document.createelement (' input ')); Boolean  

In fact, this is a common method of determining browser compatibility. The jquery library took advantage of this trick. Above, we create a new INPUT element and determine if the Pattern property browser is recognized. If so, this feature is supported by the browser. Otherwise, of course, it is not supported.

<script>if (! ') Pattern ' in document.createelement (' input ')} {    //do Client/server side validation}</script>

Keep in mind that this method relies on JavaScript.

22. Mark elements (Mark Element)

Think of <mark> elements as highlighting. The string that this label wraps should be associated with the user's current action. For example, when I search for "Beichuan" on some blogs, I can use some JavaScript to wrap the current result string with the mark tag.

23. When to use Div

Some of us started questioning exactly when to use Div. Now we can use headers, article, sections, and footer, as well as the opportunity to use div ... It? Of course.

Div should be used when there are no better elements.

For example, if you find that you need to wrap a block of code within a packaging unit that handles content targeting. However, if you are wrapping a blog post, or, perhaps, a list of links at the bottom, consider using the <article> and <nav> elements separately because they are more semantic.

24, what can begin to use immediately

It is a huge mistake to talk about the HTML5 of the present until 2022, and many people completely ignore it. In fact, there are a few HTML5 features that we can use in all of our projects! Simpler, cleaner code is always a good thing. In today's video quick show tips, I'll show you some of the options available.

Zxx:youtube video, Need FQ.

25. What's not a HTML5 (what's not HTML5)

It is understandable that those who simply assume that the transition to less javascript in their hypothetical image is all HTML5, hey, even Apple unwittingly pushes the idea. For non-developers, who cares about this, it is a simple way to apply to modern web page standards. However, for us, although it may only be semantic, it is important to understand exactly what is not HTML5.

    1. SVG: not HTML5, at least 5 years old.
    2. CSS3: not HTML5, it is ... Css.
    3. geolocation: not HTML5. //zxx:geolocation (geographic location): With HTML 5, you should be able to enable your Web application to determine your location and provide you with more relevant information.
    4. client Storage: non-HTML5, although a bit pertinent, is excluded from the specification because worrying about it as a whole can become overly complex. It now has its own specifications.
    5. Web Sockets: not HTML5, the same, has its own set of guidelines.

No matter how different your needs are, all of these technologies can be categorized as a modern network stack. In fact, many of these branch specifications are managed by the same person.

26. Data attribute (the data Attribute)

We can now formally allow all HTML elements to support custom attributes. In the past, however, we may have:

<H1 Id=someid customattribute=value> Sample, the gall is very fat 

... The checker will make a fuss! But now, as long as we define our custom attributes with the "data" prefix, the piracy attribute is instantly turned into a genuine one. If you find that you have attached an important data to a property such as class, it may be useful for JavaScript, so this property will help a lot.

HTML fragment

<div id= "mydiv" data-custom-attr= "My Value" > Balabala, Lady Gaga </div>

Retrieving the value of a custom property

var thediv = document.getElementById (' mydiv '), var attr = Thediv.getattribute (' data-custom-attr '); alert (attr); My Value

This property can also be used in CSS, such as the following example of a somewhat goofy CSS text change:

CSS code:. data_custom {display:inline-block; position:relative;}. data_custom:hover {color:transparent;}. Data_custom:hover:after {    content:attr (data-hover-response);    Color:black;    Position:absolute;    left:0;}
HTML code:<a class= "Data_custom" data-hover-response= "I said Don't touch me! "Href=" # > Don't touch me, ya minute fly butterfly ~~</a>

If your browser supports the after pseudo-class, and the Attr property of the content, you can see an effect similar to the following (IE8 is different):

To see the effect shown, you can click here: CSS and HTML5 custom properties Demo

Also, the content property is actually a very powerful property, because the low version of IE is not supported, so this property is not popular, about the content generation technology, you can see my previous "CSS content generation Technology and application" this article.

27. Output Element

As you might expect, the output element is used to display part of the calculation, for example, if you want to display the position of a mouse, or the sum of the coordinates of a series of numbers, this data should be inserted into the output element.

As a simple example, when the Submit button is pressed, we use JavaScript to insert the two number addition value into the empty output.

<form action= "" method= "get" >    <p>        5 = <output name= "sum" ></output>    </p >    <button type= "Submit" > Calculation </button></form> (function () {    var f = document.forms[0];    if (typeof f[' sum ']!== ' undefined ') {        f.addeventlistener (' Submit ', function (e) {            f[' sum '].value =-);            E.preventdefault ();        }, False);    } else {        alert (' Your browser is not ready! ');     }}) ();

Test yourself, it seems that now only in Opera browser has a good effect:

If you are using a newer version of the Opera browser now, you can click here: HTML5 result Output Box Demo

This element can also accept a property that reflects the name of the output-related element, similar to how the label works.

28. Create sliders with the range input using the zone input

HTML5 introduced the range type of input.

<input type= "Range" >  

Most notably, it can receive Min, Max, step, and value properties, and so on. While it seems that only the Opera browser fully supports this type of input, it will be fantastic when we can actually use it!

See the Quick demo below:

First Step: Tags

First, create a label
<form method= "POST" >    
Step Two: CSSBelow, we're going to use a little bit of style. We will use: Before and: After to inform the user of the maximum and minimum values we have set.
input {font-size:14px; font-weight:bold;  } Input[type=range]:before {content:attr (min); padding-right:5px;} Input[type=range]:after {content:attr (max); padding-left:5px;} Output {    display:block;    font-size:5.5em;    Font-weight:bold;}
Step three: JavaScriptFinally, we
    • detects if our browser knows range input, and if not, displays a prompt.
    • dynamically changes the value of output when the user moves the slider.
    • listens when the user leaves the slider, inserting values while locally storing.
    • Then, the next time the user refreshes the page, the selected range and values are automatically set to their last selection.
(function () {    var f = document.forms[0],        range = f[' range '],        result = f[' result '],        cachedrangevalue = Localstorage.rangevalue? Localstorage.rangevalue:5;     Detects if the browser is cool enough    //recognizes range input.    var o = document.createelement (' input ');    O.type = ' range ';    if (O.type = = = ' text ') alert (' Sorry, your browser isn't cool enough, try the latest opera browser. ');    Set the initial value    //Whether or not locally stored, the value is set to 5    range.value = Cachedrangevalue;    Result.value = Cachedrangevalue;    When the user selects a value, update the local storage    range.addeventlistener ("MouseUp", function () {        alert ("The value you selected is:" + Range.value + ".) I am now saving this value with local storage. Refresh and detect on a modern browser. ");        Localstorage? (Localstorage.rangevalue = range.value): Alert ("The data is saved to a database or somewhere else.") ");    }, False);    Show selected values when sliding    range.addeventlistener ("Change", function () {        result.value = Range.value;    }, False);}) ();

28 HTML5 features, tips and techniques you must know

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.