HTML 5
Introduction
HTML5 refers to a dozen or more separate standards.In fact, HTML5 has come to mean “HTML5 and all its related standards”. To learn HTML 5, you need some experiences:
- Web page writing
- Style sheet experience
- JavaScript experience
Because HTML is a living language, an HTML page will never become obsolete and stop working. HTML pages will never need a version number.
The HTML5 Doctype
The first line of every HTML5 document is a special code called doctype which announces to anyone who’s reading the document markup that HTML5 content follows:
<!DOCTYPE html>
Character Encoding
HTML5 lets you to add the meta element to tell the browser which character encoding is used in this HTML 5 document:
<head> <meta charset="utf-8"> </head>
The Language
To specify the language of some content, you use the lang attribute on any element, along with the appropriate language code. The easiest way to add language information to your web page is to use the element:
<html lang="en">
Adding a Style Sheet
You specify the style sheets you want to use by adding elements to the section of an HTML5 document:
<head> <link href="styles.css" rel="stylesheet"> </head>
Adding JavaScript
You can references an external file with JavaScript code:
<head> <script src="scripts.js"> </scrip> </head>
The Loosened Rules
- In HTML5, <html>, <head>, and <body> elements are optional.
- Closing slash is omitted for a void element—that’s an element with no nested content such as <br>
- Attribute values don’t need quotation marks anymore, as long as the value doesn’t include a restricted character (typically <>>, <=>, or a space).
HTML5 Validation
- http://validator.w3.org
The Return of XHTML
To turn an HTML5 document into an XHTML5 document, you need to explicitly add the XHTML namespace to the element, close every element, make sure you use lowercase tags, and so on.<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
If you want to go XHTML5 all the way, you need to configure your web server to serve your page with the MIME type application/xhtml+xml or application/xml, instead of the standard text/html.
Feature Detection with Modernizr
Checking for support usually involves looking for a property on a programming object, or creating an object and trying to use it a certain way. Consider using Modernizr
(www.modernizr.com), a small, constantly updated tool that tests the support of a wide range of HTML5 and related features.
- Download the Modernizr script The full Modernizr script is a bit bulky. It’s intended for testing purposes while you’re still working on your website. Once you’ve finished development and you’re ready to go live, you can create a slimmed down version of the Modernizr script that tests only for the features you need. After the Modernizr script runs, it tests for a couple of dozen new features and then creates a JavaScript object called Modernizr that contains the results. You can test the properties of this object to check the browser’s support for a specific feature.
- Add a reference to the downloaded JavaScript file <script src="modernizr.js"></script>
- Write some script code that tests for the feature you want and then carries out the appropriate action. You can use the basic and time-honored JavaScript techniques—looking up an element by ID and changing its content.
<p>The verdict is... <span id="result"></span></p> <script> var result = document.getElementById("result"); if (Modernizr.draganddrop) { result.innerHTML = "Rejoice! Your browser supports drag-and-drop."; } else { result.innerHTML = "Your feeble browser doesn't support drag-and-drop."; } </script>
A New Way to Structure Pages
Introducing the Semantic Elements
To improve the structure of your web pages, you need HTML5’s new semantic elements. These elements give extra meaning to the content they enclose. The majority of the new elements in HTML5 are semantic elements.
All the semantic elements share a distinguishing feature: They don’t really do anything. The purpose is to:
- Easier editing and maintenance.
- Accessibility
- Search-engine optimization Search engines check for some of HTML5’s semantic elements to get more information about the pages they’re indexing.
Retrofitting a Traditional HTML Page
Page Structure the Old Way
In a well-written, traditional HTML page, most of the work is farmed out to the style sheet using the <div> and <span> containers. The <span> lets you
format snippets of text inside another element. The <div> allows you to format entire sections of content, and it establishes the overall structure of the page.
The use of contextual selectors are used with the style sheet.
Page Structure with HTML5
The limitation of the <div> is that it doesn’t provide any information about the page, you don’t know the purpose of that section.
To improve this situation in HTML5, you can replace some of your <div> elements with more descriptive semantic elements. The semantic elements behave exactly like
a <div> element.However, they also add a little bit more semantic to your page.
For ex., the HTML 5 elements : <header>, <footer> and <article>.
Subtitles with <hgroup>
The <hgroup> tag is used to group a set of <h1> to <h6> elements, when a heading has multiple levels (subheadings).
Adding a Figure with <figure>
You can think of them much like figures in a book, a picture that’s separate from the text, yet referred to in the text.
Adding a Sidebar with <aside>
To introduce a related topic or to expand on a point that’s raised in the text that surrounds it.
Browser Compatibility for the Semantic Elements
Most of HTML5’s semantic elements and the semantic elements don’t actually do anything. Web browsers that don’t recognize the HTML5 elements won’t know to display some
of them as block elements.
To fix this problem, you simply need to add a new rule to your style sheet that applies block display formatting to the nine HTML5 elements:
article, aside, figure, figcaption, footer, header, hgroup, nav, section, summary { display: block; }Old versions of IE refuse to apply style sheet formatting to elements they don’t recognize. You can trick IE into recognizing a foreign element by registering it with a JavaScript command:
document.createElement('header')
Designing a Site with the Semantic Elements
Deeper into Headers
To turn web pages into websites, you can use 2 ways:
- Server-side frameworks
- Page templates
Navigation Links with <nav>
You can use <nav> to designate an entirely separate section of the page—one that’s offset from the main flow. The <nav> element wraps a block of links.Deeper into Footers
The footer is supposed to be limited to a few basic details about the website’s copyright, authorship, legal restrictions, and links. Footers aren’t supposed to hold long lists of links, important pieces of content, or extraneous details like ads, social media buttons, and website widgets.
If you have a <footer> that applies to some piece of content, your <footer> needs to be placed inside the element that wraps that content.
Deeper into Sections
If you have a titled block of content, and the other semantic elements aren’t appropriate, then the <section> element is generally a better choice than <div>.
The HTML5 Outlining System
HTML5 defines a set of rules that dictate how you can create a document outline for any web page. However, almost no one uses HTML5 outlines today.
Basic Outlines
To visualize the outline of your web page, imagine it stripped of all content except for the text in a numbered heading element (<h1>, <h2>, <h3>, and so on).
Sectioning Elements
Sectioning elements are elements that create a new, nested outline inside your page. These elements are <article>, <aside>, <nav>, and <section>.
Meaningful Markup
Semantics are all about adding meaning to your markup, and there are several types of information you can inject.Semantic elements can give your pages a clean, logical structure — you used them to explain the purpose of large blocks of content and entire sections of your layout. But semantics can also include text-level information, which you add to explain much smaller pieces of content.
The Semantic Elements Revisited
Dates and Times with <time>
The <time> element allows you to mark up a date, time, or combined date and time.
JavaScript Calculations with <output>
The <output> element is a nothing more than a placeholder that your code can use to show a piece of calculated information.
The usual way of dealing with this is to assign a unique ID to the placeholder, so the JavaScript code can find it when it performs the calculation. Typically, web developers use the <span> element, which works perfectly but doesn’t provide any specific meaning. That is more meaningful if you use the <output> to do the same thing.
Highlighted Text with <mark>
The <mark> element represents a section of text that’s highlighted for reference. It’s particularly appropriate when you’re quoting someone else’s text, and you want to
bring attention to something. By default, marked-up text is highlighted with a bright yellow background.
Other Standards that Boost Semantics
There were plenty of web developers clamoring for ways to make their markup for meaningful before HTML 5 was developed.
- ARIA (Accessible Rich Internet Applications) ARIA is a developing standard that lets you supply extra information for screen readers through attributes on any HTML element.
- RDFa (Resource Description Framework) RDFa is a standard for embedding detailed metadata into your web documents using attributes.
- Microformats The hCard microformat is an all-purpose way to represent the contact information. To create an hCard, you need a root element that sets the class attribute to vcard. Inside that element, you need to supply at least a formatted name, in another element. That element needs to set the class attribute to fn. You can get information about all the supported hCard properties at http://microformats.org/wiki/hcard.
- Microdata It began its life as part of the HTML5 specification, and later split into its own developing standard at http://dev.w3.org/html5/md. To begin a microdata section, you add the itemscope and itemtype attributes to any element. The itemscope attribute indicates that you’re starting a new chunk of semantic content. The itemtype attribute indicates the specific type of data you’re encoding.
Google Rich Snippets
All you do is put the right semantic data on your page, and Google will find it and use it to present a fancier search listing, which can help your website stand out from the crowd. Rich snippets is the name Google has created to lump together RDFa, microformats, and microdata.
To learn more about the standards that rich snippets support, you can view Google’s documentation at http://tinyurl.com/GoogleRichSnippets.
To see how Google’s rich snippets feature works, you can use Google’s Rich Snippets Testing Tool:
- Go to www.google.com/webmasters/tools/richsnippets
- Enter the full URL to your page in the text box
- Click Preview
Web Forms, Refined
HTML forms are simple HTML controls you use to collect information from website visitors.
Understanding Forms
A web form is a collection of text boxes, lists, buttons, and other clickable widgets that a web surfer uses to supply some sort of information to a website.
It’s worth noting that forms aren’t the only way to send user-entered information to a web server (although they were, once upon a time). Today, crafty developers can use the XMLHttpRequest object in JavaScript code to quietly communicate with a web server. Someforms don’t need any help from the server, so they can perform their
calculations entirely in JavaScript and display the result on the current page.
Revamping a Traditional HTML Form
A well-designed form divides itself into logical chunks using the <fieldset> element.
The <fieldset> tag is used to group related elements in a form and draws a box around the related elements.
Adding Hints with Placeholders
You don’t need placeholders for every text box. Instead, you should use them to clear up potential ambiguity. Sometimes placeholders include a sample value.
To create a placeholder, simply use the placeholder attribute on the input element.
Focus: Starting in the Right Spot
HTML5’s new autofocus attribute which you can add to a single <input> or <textarea> element.
Validation: Stopping Errors
The HTML5 invented a way for browsers to help to do the validation work instead of web developers.
They devised a client-side validation system that lets you embed common error-checking rules into any <input> field.
How HTML5 Validation Works
Validation kicks in only when the form filler clicks a button to submit the form, different attributes let you apply different. All the validation conditions must be met before the form can
be submitted. You can apply more than one rule to the same input box and apply more than one rule to the same input box.
The form filler needs to supply some sort of information by using <input required>
Turning Validation Off
To turn validation off for an entire form, you add the novalidate attribute to the containing <form> element:
<form novalidate>
Validation Styling Hooks
- required and optional, which apply styles to fields based on whether they use the required attribute.
- valid and invalid, which apply styles to controls based on whether they contain mistakes. But remember that most browsers won’t actually discover invalid values until the visitor tries to submit the form, so you won’t see the invalid formatting right away.
- in-range and out-of-range, which apply formatting to controls that use the min and max attributes to limit numbers to a range
Validating with Regular Expressions
Once you have a regular expression, you can enforce it in any <input> or <textarea> element by adding the pattern attribute:
Custom Validation
The HTML5 specification also outlines a set of JavaScript properties that force the browser to validate if fields are valid
To check the appropriate field for errors. You do this by providing the callback to the onInput event:
<textarea oninput=validateCallback(this)>The onInput event triggers the assigned callback function then you can check if the current input value has problems inside the callback function. If the input is wrong, you can supply an error message in setCustomValidity(); otherwise, you need to call setCustomValidity() with an empty string. This clears any error custom messages that you may set earlier.
Browser Support for Validation
Some browser builds support some validation features while ignoring others.
New Types of Input
If a browser runs into an <input> element with a type that it doesn’t recognize, the browser treats it like an ordinary text box. new HTML5 input types:
- url
- search*
- tel*
- number
- range
- datetime,date,month,week,time
- color
New Elements
New Types of Input
An HTML Editor in a Web Page
Audio and Video
Understanding Video Today
Without HTML5, you have a couple of ways to add video to a web page:
- <embed> element The browser then creates a video window that uses some video player, and places it on the page.
- browser plug-in Adobe Flash.
Introducing HTML5 Audio and Video
Making Some Noise with <audio>
<audio src="filename" controls preload="" autoplay loop ></audio>where
- The src attribute provides the file name of the audio file you want to play.
- The controls attribute tells the browser to include a basic set of playback controls. Each browser has a slightly different version of these controls.
- The <audio> element supports three more attributes: preload, autoplay, and loop. preload: When you use the none or metadata values, the browser downloads the audio file as soon as someone clicks the play button. The preload attribute also supports two more values:
- metadata: To tell the browser to grab the first small chunk of data from the file, which is enough to determine some basic details (like the total length of the audio).
- none: To tell the browser to hold off completely
The autoplay attribute, which tells the browser to start playback immediately once the page has finished loading. To get background music, remove the controls attribute and add the autoplay attribute but remember to provide a mute button that uses JavaScript to silence the audio.
The loop attribute tells the browser to start over at the beginning when the
audio ends
Getting the Big Picture with <video>
<video src="filename" controls preload="" autoplay loop width="pixels" height="pixels" poster="filename" ></video>
It has the same src, controls, preload, autoplay, and loop attributes as the <audio> element but with additional attributes:
- The height and width attributes set the size of the video window (in pixels).
- The poster attribute lets you supply an image that should be used in place of the video. Browsers use this picture in three situations: if the first frame of the video hasn’t been downloaded yet, if you’ve set the preload attribute to none, or if the selected video file wasn’t found.
Format Wars and Fallbacks
Meet the Formats
The official HTML5 standard doesn’t require support for any specific video or audio format, browser makers are free to choose the formats they want to support.Browser Support for Media Formats
Some features, like autoplay and looping, may not be supported in mobile browsers.Multiple Formats: How to Please Every Browser
No single audio or video format can work on all browsers.The <source> Element
The first step to support multiple formats is to remove the src attribute from the <video> or <audio> element, and replace it with a list of nested <source> elements inside. Each <source> element points to a separate audio file. The browser then chooses the first file it finds that has a format it supports.<audio controls> <source src="filename1" type="MIME-TYPE"> <source src="filename2g" type="MIME-TYPE"> </audio>the type attribute is used to supply the correct MIME type so that the browser will attempt to download only a file it believes it can play.
The Flash Fallback
Every browser ignores unrecognized tags but don’t ignore the content inside unrecognized element. This fallback content provides a seamless way to deal with older browsers.The proper thing to include for fallback content is another working window—in other words, whatever you’d use in an ordinary, non-HTML5 page.
留言