HTML4 与 HTML5 的区别

    xiaoxiao2021-04-18  83

    Abstract

    "Differences from HTML4" describes the differences of the HTML specification from those of HTML4.

    Table of Contents

    1 Introduction 1.1 Scope of This Document 1.2 History of HTML 1.3 Open Issues 1.4 Backward Compatibility 1.5 Development Model 2 Syntax 2.1 Character Encoding 2.2 The Doctype 2.3 MathML and SVG 2.4 Miscellaneous 3 Language 3.1 New Elements 3.2 New Attributes 3.3 Changed Elements 3.4 Changed Attributes 3.5 Obsolete Elements 3.6 Obsolete Attributes 4 Content Model 5 APIs 5.1 New APIs 5.2 Changed APIs 5.3 Extensions to Document 5.4 Extensions to HTMLElement 5.5 Extensions to Other Interfaces 5.6 Obsolete APIs Acknowledgments References

    1 Introduction

    1.1 Scope of This Document

    This document covers the WHATWG HTML standard. It does not cover the W3C HTML5 or W3C HTML5.1 specifications. [HTML] [HTML5] [HTML5NIGHTLY]

    1.2 History of HTML

    HTML has been in continuous evolution since it was introduced to the Internet in the early 1990s. Some features were introduced in specifications; others were introduced in software releases. In some respects, implementations and Web developer practices have converged with each other and with specifications and standards, but in other ways, they have diverged.

    HTML4 became a W3C Recommendation in 1997. While it continues to serve as a rough guide to many of the core features of HTML, it does not provide enough information to build implementations that interoperate with each other and, more importantly, with Web content. The same goes for XHTML1, which defines an XML serialization for HTML4, and DOM Level 2 HTML, which defines JavaScript APIs for both HTML and XHTML. HTML replaces these documents. [DOM2HTML] [HTML4] [XHTML1]

    The HTML specification reflects an effort, started in 2004, to study contemporary HTML implementations and Web content. The specification:

    Defines a single language called HTML which can be written in HTML syntax and in XML syntax.

    Defines detailed processing models to foster interoperable implementations.

    Improves markup for documents.

    Introduces markup and APIs for emerging idioms, such as Web applications.

    1.3 Open Issues

    See open issues in Bugzilla. The specification also has annotation boxes in the margin which can link to bugs.

    1.4 Backward Compatibility

    HTML is defined in a way that is backward compatible with the way user agents handle content. To keep the language relatively simple for Web developers, several older elements and attributes are not included, as outlined in the other sections of this document, such as presentational elements that are better handled using CSS.

    User agents, however, will always have to support these older elements and attributes. This is why the HTML specification clearly separates requirements for Web developers (referred to as "authors" in the specification) and user agents; for instance, this means that Web developers cannot use the isindex or the plaintext element, but user agents are required to support them in a way that is compatible with how these elements need to behave for compatibility with Web content.

    Since HTML has separate conformance requirements for Web developers and user agents there is no longer a need for marking features "deprecated".

    1.5 Development Model

    The HTML4 specification reached Recommendation status before it was completely implemented in user agents. HTML4 still is not completely implemented, because it contains various bugs that have been fixed in the current HTML specification, which user agents are much closer to implementing than HTML4.

    The HTML standard is under continual development where bugs are fixed and new features are introduced over time. Features can also be removed from the specification if they lack implementor interest, are not being used by Web developers, or for other reasons.

    2 Syntax

    HTML defines a syntax, referred to as "the HTML syntax", that is mostly compatible with HTML4 and XHTML1 documents published on the Web, but is not compatible with the more esoteric SGML features of HTML4, such as processing instructions and shorthand markup as these are not supported by most user agents. Documents using the HTML syntax are served with the text/html media type.

    HTML also defines detailed parsing rules (including "error handling") for this syntax which are largely compatible with HTML4-era implementations. User agents have to use these rules for resources that have the text/html media type. Here is an example document that conforms to the HTML syntax:

    <!doctype html> <html> <head> <meta charset="UTF-8"> <title>Example document</title> </head> <body> <p>Example paragraph</p> </body> </html>

    The other syntax that can be used for HTML is XML. This syntax is compatible with XHTML1 documents and implementations. Documents using this syntax need to be served with an XML media type (such as application/xhtml+xml or application/xml) and elements need to be put in the http://www.w3.org/1999/xhtml namespace following the rules set forth by the XML specifications. [XML] [XMLNS]

    Below is an example document that conforms to the XML syntax of HTML.

    <?xml version="1.0" encoding="UTF-8"?> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Example document</title> </head> <body> <p>Example paragraph</p> </body> </html>

    2.1 Character Encoding

    For the HTML syntax, Web developers are required to declare the character encoding. There are three ways to do that:

    At the transport level; for instance, by using the HTTP Content-Type header.

    Using a Unicode Byte Order Mark (BOM) character at the start of the file. This character provides a signature for the encoding used.

    Using a meta element with a charset attribute that specifies the encoding within the first 1024 bytes of the document; for instance, <meta charset="UTF-8"> could be used to specify the UTF-8 encoding. This replaces the need for <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> although that syntax is still allowed.

    For the XML syntax, Web developers have to use the rules as set forth in the XML specification to set the character encoding.

    2.2 The Doctype

    The HTML syntax requires a doctype to be specified to ensure that the browser renders the page in standards mode. The doctype has no other purpose. [DOCTYPE]

    In HTML4, it was possible to use doctypes that were syntactically correct but still trigger quirks mode (e.g. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">, without the URL).

    If you were using no doctype or a quirky doctype and switch to a standards mode doctype, you will most likely run into differences between the modes. For example, in quirks mode, classes and IDs in Selectors are case-insensitive and CSS <length>s do not require a unit. For more examples, please refer to What happens in Quirks Mode?.

    The doctype declaration for the HTML syntax is <!DOCTYPE html> and is case-insensitive. Doctypes from earlier versions of HTML were longer because the HTML language was SGML-based and therefore required a reference to a DTD. This is no longer the case and the doctype is only needed to enable standards mode for documents written using the HTML syntax. Browsers already do this for <!DOCTYPE html>.

    To support legacy markup generators that cannot generate the preferred short doctype, the doctype <!DOCTYPE html SYSTEM "about:legacy-compat"> is allowed in the HTML syntax.

    The strict doctypes for HTML 4.0, HTML 4.01, XHTML 1.0 as well as XHTML 1.1 are also allowed (but are discouraged) in the HTML syntax.

    In the XML syntax, any doctype declaration may be used, or it may be omitted altogether. Documents with an XML media type are always handled in standards mode.

    2.3 MathML and SVG

    The HTML syntax allows for MathML and SVG elements to be used inside a document. An math or svg start tag causes the HTML parser to switch to a special insertion mode which puts elements and attributes in the appropriate namespaces, does case fixups for elements and attributes that have mixed case, and supports the empty-element syntax as in XML. The syntax is still case-insensitive and attributes allow the same syntax as for HTML elements. Namespace declarations may be omitted. CDATA sections are supported in this insertion mode.

    Some MathML and SVG elements cause the parser to switch back to "HTML mode", e.g. mtext and foreignObject, so you can use HTML elements or a new math or svg element.

    For instance, a very simple document using some of the minimal syntax features could look like:

    <!doctype html> <title>SVG in text/html</title> <p> A green circle: <svg> <circle r="50" cx="50" cy="50" fill="green"/> </svg> </p>

    2.4 Miscellaneous

    There are a few other changes in the HTML syntax worthy of mentioning:

    The ⟨ and ⟩ named character references now expand to U+27E8 and U+27E9 (mathematical left/right angle bracket) instead of U+2329 and U+232A (left/right-pointing angle bracket), respectively.

    Many new named character references have been added, including all named character references from MathML.

    Void elements (known as "EMPTY" in HTML4) are allowed to have a trailing slash.

    The ampersand (&) may be left unescaped in more cases compared to HTML4.

    Attributes have to be separated by at least one whitespace character.

    Attributes with an empty value may be written as just the attribute name omitting the equals sign and the value, even if the attribute is not a boolean attribute. (It is commonly believed that HTML4 allowed the value to be omitted for boolean attributes. Instead, HTML4 allowed using only the attribute value and omitting the attribute name, for enumerated attributes, but this was not supported in browsers.)

    Attributes omitting quotes for the value are allowed to use a larger set of characters compared to HTML4.

    The HTML parser does not do any normalization of whitespace in attribute values; for instance, leading and trailing whitespace in the id attribute is not ignored (and thus now invalid), and newline characters can be used in the value attribute of the input element without using character references.

    The optgroup end tag is now optional.

    The colgroup start tag is now optional and is inferred by the HTML parser.

    3 Language

    This section is split up in several subsections to more clearly illustrate the various differences from HTML4.

    3.1 New Elements

    The following elements have been introduced for better structure:

    section represents a generic document or application section. It can be used together with the h1, h2, h3, h4, h5, and h6 elements to indicate the document structure.

    article represents an independent piece of content of a document, such as a blog entry or newspaper article.

    main can be used as a container for the dominant contents of another element, such as the main content of the page.

    aside represents a piece of content that is only slightly related to the rest of the page.

    hgroup represents the header of a section.

    header represents a group of introductory or navigational aids.

    footer represents a footer for a section and can contain information about the author, copyright information, etc.

    nav represents a section of the document intended for navigation.

    figure represents a piece of self-contained flow content, typically referenced as a single unit from the main flow of the document.

    <figure> <video src="example.webm" controls></video> <figcaption>Example</figcaption> </figure>

    figcaption can be used as caption (it is optional).

    template can be used to declare fragments of HTML that can be cloned and inserted in the document by script.

    Then there are several other new elements:

    video and audio for multimedia content. Both provide an API so application Web developers can script their own user interface, but there is also a way to trigger a user interface provided by the user agent. source elements are used together with these elements if there are multiple streams available of different types.

    track provides text tracks for the video element.

    embed is used for plugin content.

    mark represents a run of text in one document marked or highlighted for reference purposes, due to its relevance in another context.

    progress represents a completion of a task, such as downloading or when performing a series of expensive operations.

    meter represents a measurement, such as disk usage.

    time represents a date and/or time.

    data allows content to be annotated with a machine-readable value.

    dialog for showing a dialog.

    ruby, rt, and rp allow for marking up ruby annotations.

    bdi represents a span of text that is to be isolated from its surroundings for the purposes of bidirectional text formatting.

    wbr represents a line break opportunity.

    canvas is used for rendering dynamic bitmap graphics on the fly, such as graphs or games.

    menuitem represents a command the user can invoke from a popup menu.

    details represents additional information or controls which the user can obtain on demand. The summary element provides its summary, legend, or caption.

    datalist together with the a new list attribute for input can be used to make comboboxes:

    <input list="browsers"> <datalist id="browsers"> <option value="Safari"> <option value="Internet Explorer"> <option value="Opera"> <option value="Firefox"> </datalist>

    keygen represents control for key pair generation.

    output represents some type of output, such as from a calculation done through scripting.

    The input element's type attribute now has the following new values:

    tel search url email datetime date month week time datetime-local number range color

    The idea of these new types is that the user agent can provide the user interface, such as a calendar date picker or integration with the user's address book, and submit a defined format to the server. It gives the user a better experience as his input is checked before sending it to the server meaning there is less time to wait for feedback.

    3.2 New Attributes

    Several attributes have been introduced to various elements that were already part of HTML4:

    The a and area elements have the new download and ping attributes.

    The area element, for consistency with the a and link elements, now also has the hreflang, type and rel attributes.

    The base element can now have a target attribute as well, mainly for consistency with the a element. (This is already widely supported.)

    The meta element has a charset attribute now as this was already widely supported and provides a nice way to specify the character encoding for the document.

    The table element now has a sortable attribute and the th element has a sorted attribute, which provide a means to sort table columns.

    A new autofocus attribute can be specified on the input (except when the type attribute is hidden), select, textarea and button elements. It provides a declarative way to focus a form control during page load. Using this feature should enhance the user experience compared to focusing the element with script as the user can turn it off if the user does not like it, for instance.

    A new placeholder attribute can be specified on the input and textarea elements. It represents a hint intended to aid the user with data entry.

    <input type=search name=q placeholder="Enter search phrase..."> <button>Search</button> <label>Email <input type=email name=email placeholder="john@example.com"></label>

    The placeholder attribute should not be used as a replacement for the label element.

    <!-- Do not do this: --> <input type=email name=email placeholder="Email">

    The new form attribute for input, output, select, textarea, button, label, object and fieldset elements allows for controls to be associated with a form. These elements can now be placed anywhere on a page, not just as descendants of the form element, and still be associated with a form.

    <table> <tr> <th>Key <th>Value <th>Action <tr> <td><form id=1><input name=1-key></form> <td><input form=1 name=1-value> <td><button form=1 name=1-action value=save>✓</button> <button form=1 name=1-action value=delete>✗</button> ... </table>

    The new required attribute applies to input (except when the type attribute is hidden, image or some button type such as submit), select and textarea. It indicates that the user has to fill in a value in order to submit the form. For select, the first option element has to be a placeholder with an empty value.

    <label>Color: <select name=color required> <option value="">Choose one <option>Red <option>Green <option>Blue </select></label>

    The fieldset element now allows the disabled attribute which disables all descendant controls (excluding those that are descendants of the legend element) when specified, and the name attribute which can be used for script access.

    The input element has several new attributes to specify constraints: autocomplete, min, max, multiple, pattern and step. As mentioned before it also has a new list attribute which can be used together with the datalist element. It also now has the width and height attributes to specify the dimensions of the image when using type=image.

    The input and textarea elements have a new attribute named dirname that causes the directionality of the control as set by the user to be submitted as well.

    The textarea element also has three new attributes, maxlength, minlength and wrap which control max input length and submitted line wrapping behavior, respectively.

    The form element has a novalidate attribute that can be used to disable form validation submission (i.e. the form can always be submitted).

    The input and button elements have formaction, formenctype, formmethod, formnovalidate, and formtarget as new attributes. If present, they override the action, enctype, method, novalidate, and target attributes on the form element.

    The input element also has the new minlength attribute.

    The input and textarea elements have an inputmode attribute.

    The menu element has two new attributes: type and label. They allow the element to transform into a menu as found in typical user interfaces as well as providing for context menus in conjunction with the global contextmenu attribute.

    The button element has a new menu attribute, used together with popup menus.

    The style element has a new scoped attribute which can be used to enable scoped style sheets. Style rules within such a style element only apply to the local tree.

    The script element has a new attribute called async that influences script loading and execution.

    The html element has a new attribute called manifest that points to an application cache manifest used in conjunction with the API for offline Web applications.

    The link element has a new attribute called sizes. It can be used in conjunction with the icon relationship (set through the rel attribute; can be used for e.g. favicons) to indicate the size of the referenced icon, thus allowing for icons of distinct dimensions.

    The ol element has a new attribute called reversed. When present, it indicates that the list order is descending.

    The iframe element has new attributes called sandbox, seamless, and srcdoc which allow for sandboxing content, e.g. blog comments.

    The object element has a new attribute called typemustmatch which allows safer embedding of external resources.

    The img element has a new attribute called crossorigin to use CORS in the fetch and if it is successful, allows the image data to be read with the canvas API. The script element has a crossorigin attribute to allow script errors to be reported to onerror with information about the error. The link element also has a crossorigin attribute.

    The img element has new attributes called srcset and sizes, along with the new elements picture and source to allow Web developers to declaratively control or give hints to the user agent about which image resource to use, based on the screen pixel density, viewport size, image format, and other factors.

    Several attributes from HTML4 now apply to all elements. These are called global attributes: accesskey, class, dir, id, lang, style, tabindex and title. Additionally, XHTML 1.0 only allowed xml:space on some elements, which is now allowed on all elements in XHTML documents.

    There are also several new global attributes:

    The contenteditable attribute indicates that the element is an editable area. The user can change the contents of the element and manipulate the markup.

    The contextmenu attribute can be used to point to a context menu provided by the Web developer.

    The data-* collection of Web developer-defined attributes. Web developers can define any attribute they want as long as they prefix it with data- to avoid clashes with future versions of HTML. These are intended to be used to store custom data to be consumed by the Web page or application itself. They are not intended for data to be consumed by other parties (e.g. user agents).

    The draggable and dropzone attributes can be used together with the new drag & drop API.

    The hidden attribute indicates that an element is not yet, or is no longer, relevant.

    The role and aria-* collection attributes which can be used to instruct assistive technology.

    The spellcheck attribute allows for hinting whether content can be checked for spelling or not.

    The translate attribute gives a hint to translators whether the content should be translated.

    HTML also makes all event handler attributes from HTML4, which take the form onevent, global attributes and adds several new event handler attributes for new events it defines; for instance, the onplay event handler attribute for the play event which is used by the API for the media elements (video and audio). The specification has an index of all events.

    3.3 Changed Elements

    These elements have slightly modified meanings in HTML to better reflect how they are used on the Web or to make them more useful:

    The b element now represents a span of text to which attention is being drawn for utilitarian purposes without conveying any extra importance and with no implication of an alternate voice or mood, such as key words in a document abstract, product names in a review, actionable words in interactive text-driven software, or an article lede.

    The cite element now solely represents the title of a work (e.g. a book, a paper, an essay, a poem, a score, a song, a script, a film, a TV show, a game, a sculpture, a painting, a theatre production, a play, an opera, a musical, an exhibition, a legal case report, etc). Specifically the example in HTML4 where it is used to mark up the name of a person is no longer considered conforming.

    The dl element now represents an association list of name-value groups, and is no longer said to be appropriate for dialogue.

    The hr element now represents a paragraph-level thematic break.

    The i element now represents a span of text in an alternate voice or mood, or otherwise offset from the normal prose in a manner indicating a different quality of text, such as a taxonomic designation, a technical term, an idiomatic phrase from another language, a thought, or a ship name in Western texts.

    For the label element the browser should no longer move focus from the label to the control unless such behavior is standard for the underlying platform user interface.

    The menu element is redefined to be useful for toolbars and popup menus.

    The noscript element is no longer said to be rendered when the user agent doesn't support a scripting language invoked by a script element earlier in the document.

    The s element now represents contents that are no longer accurate or no longer relevant.

    The script element can now be used for scripts or for custom data blocks.

    The small element now represents side comments such as small print.

    The strong element now represents importance rather than strong emphasis.

    The u element now represents a span of text with an unarticulated, though explicitly rendered, non-textual annotation, such as labeling the text as being a proper name in Chinese text (a Chinese proper name mark), or labeling the text as being misspelt.

    3.4 Changed Attributes

    Several attributes have changed in various ways.

    The alt attribute on img has more elaborate requirements, and in some cases can also be omitted. For details, see the specification.

    The accept attribute on input now allows the values audio/*, video/* and image/*.

    The accesskey global attribute now allows multiple characters to be specified, which the user agent can choose from.

    The action attribute on form is no longer allowed to have an empty URL.

    The method attribute has a new keyword dialog, intended to close a dialog element.

    The colspan attribute on td and th now has to be greater than zero.

    The coords attribute on area no longer allows a percentage value of the radius when the element is in the circle state.

    The data attribute on object is no longer said to be relative to the codebase attribute.

    The defer attribute on script now explicitly makes the script execute when the page has finished parsing.

    The dir global attribute now allows the value auto.

    The enctype attribute on form now supports the value text/plain.

    The width and height attributes on img, iframe and object are no longer allowed to contain percentages. They are also not allowed to be used to stretch the image to a different aspect ratio than its intrinsic aspect ratio.

    The href attribute on link is no longer allowed to have an empty URL.

    The href attribute on base is now allowed to contain a relative URL.

    All attributes that take URLs, e.g. href on the a element, now support IRIs if the document's encoding is UTF-8 or UTF-16.

    The http-equiv attribute on meta is no longer said to be used by HTTP servers to create HTTP headers in the HTTP response. Instead, it is said to be a pragma directive to be used by the user agent.

    The id global attribute is now allowed to have any value, as long as it is unique, is not the empty string, and does not contain space characters.

    The lang global attribute takes the empty string in addition to a valid language identifier, just like xml:lang does in XML.

    The media attribute on link now accepts a media query list and defaults to "all".

    The event handler attributes (e.g. onclick) now always use JavaScript as the scripting language.

    The value attribute of the li element is no longer deprecated as it is not presentational. The same goes for the start and type attributes of the ol element.

    The style global attribute now always uses CSS as the styling language.

    The tabindex global attribute now allows negative values which indicate that the element can receive focus but cannot be tabbed to.

    The target attribute of the a and area elements is no longer deprecated, as it is useful in Web applications, e.g. in conjunction with iframe.

    The type attribute on script and style is no longer required if the scripting language is JavaScript and the styling language is CSS, respectively.

    The usemap attribute on img no longer takes a URL, but instead takes a valid hash-name reference to a map element.

    3.5 Obsolete Elements

    The elements in this section are not to be used by Web developers. User agents will still have to support them and various sections in HTML define how. E.g. the obsolete isindex element is handled by the parser section.

    The following elements are not in HTML because their effect is purely presentational and their function is better handled by CSS:

    basefont big center font strike tt

    The following elements are not in HTML because using them damages usability and accessibility:

    frame frameset noframes

    The following elements are not included because they have not been used often, created confusion, or their function can be handled by other elements:

    acronym is not included because it has created a lot of confusion. Web developers are to use abbr for abbreviations.

    applet has been obsoleted in favor of object.

    isindex usage can be replaced by usage of form controls.

    dir has been obsoleted in favor of ul.

    Finally the noscript element is only conforming in the HTML syntax. It is not allowed in the XML syntax. This is because in order to not only hide visually but also prevent the content to run scripts, apply style sheets, have submittable form controls, load resources, and so forth, the HTML parser parses the content of the noscript element as plain text. The same is not possible with an XML parser.

    3.6 Obsolete Attributes

    Some attributes from HTML4 are no longer allowed in HTML. The specification defines how user agents should process them in legacy documents, but Web developers are not allowed use them and they will not validate.

    HTML has advice on what you can use instead.

    rev and charset attributes on link and a.

    shape and coords attributes on a.

    longdesc attribute on img and iframe.

    target attribute on link.

    nohref attribute on area.

    profile attribute on head.

    version attribute on html.

    name attribute on img (use id instead).

    scheme attribute on meta.

    archive, classid, codebase, codetype, declare and standby attributes on object.

    valuetype and type attributes on param.

    axis attribute on td and th.

    abbr and scope attributes on td.

    summary attribute and border attribute on table.

    accept attribute on form.

    usemap attribute on input.

    In addition, HTML has none of the presentational attributes that were in HTML4 as their functions are better handled by CSS:

    align attribute on caption, iframe, img, input, object, legend, table, hr, div, h1, h2, h3, h4, h5, h6, p, col, colgroup, tbody, td, tfoot, th, thead and tr.

    alink, link, text and vlink attributes on body.

    background attribute on body.

    bgcolor attribute on table, tr, td, th and body.

    border attribute on object.

    cellpadding and cellspacing attributes on table.

    char and charoff attributes on col, colgroup, tbody, td, tfoot, th, thead and tr.

    clear attribute on br.

    compact attribute on dl, menu, ol and ul.

    frame attribute on table.

    frameborder attribute on iframe.

    height attribute on td and th.

    hspace and vspace attributes on img and object.

    marginheight and marginwidth attributes on iframe.

    noshade attribute on hr.

    nowrap attribute on td and th.

    rules attribute on table.

    scrolling attribute on iframe.

    size attribute on hr.

    type attribute on li, and ul.

    valign attribute on col, colgroup, tbody, td, tfoot, th, thead and tr.

    width attribute on hr, table, td, th, col, colgroup and pre.

    The following attributes are allowed but Web developers are discouraged from using them and instead strongly encouraged to use an alternative solution:

    The border attribute on img. It is required to have the value "0" when present. Web developers can use CSS instead.

    The language attribute on script. It is required to have the value "JavaScript" (case-insensitive) when present and cannot conflict with the type attribute. Web developers can simply omit it as it has no useful function.

    The name attribute on a. Web developers can use the id attribute instead.

    4 Content Model

    The content model is what defines how elements may be nested — what is allowed as children (or descendants) of a certain element.

    At a high level, HTML4 had two major categories of elements, "inline" (e.g. span, img, text), and "block-level" (e.g. div, hr, table). Some elements did not fit in either category.

    Some elements allowed "inline" elements (e.g. p), some allowed "block-level" elements (e.g. body), some allowed both (e.g. div), while other elements did not allow either category but only allowed other specific elements (e.g. dl, table), or did not allow any children at all (e.g. link, img, hr).

    Notice the difference between an element itself being in a certain category, and having a content model of a certain category; for instance, the p element is itself a "block-level" element, but has a content model of "inline".

    To make it more confusing, HTML4 had different content model rules in its Strict, Transitional and Frameset flavors; for instance, in Strict, the body element allowed only "block-level" elements, but in Transitional, it allowed both "inline" and "block-level".

    To make things more confusing still, CSS uses the terms "block-level element" and "inline-level element" for its visual formatting model, which is related to CSS's 'display' property and has nothing to do with HTML's content model rules.

    HTML does not use the terms "block-level" or "inline" as part of its content model rules, to reduce confusion with CSS. However, it has more categories than HTML4, and an element can be part of none of them, one of them, or several of them.

    Metadata content, e.g. link, script.

    Flow content, e.g. span, div, text. This is roughly like HTML4's "block-level" and "inline" together.

    Sectioning content, e.g. aside, section.

    Heading content, e.g. h1.

    Phrasing content, e.g. span, img, text. This is roughly like HTML4's "inline". Elements that are phrasing content are also flow content.

    Embedded content, e.g. img, iframe, svg.

    Interactive content, e.g. a, button, label. Interactive content is not allowed to be nested.

    As a broad change from HTML4, HTML no longer has any element that only accepts what HTML4 called "block-level" elements; e.g. the body element now allows flow content. Thus, This is closer to HTML4 Transitional than HTML4 Strict.

    Further changes include:

    The address element now allows flow content, but with no heading content descendants, no sectioning content descendants, and no header, footer, or address element descendants.

    HTML4 allowed object in head. HTML does not.

    The link and meta elements are allowed as descendants of body if they use microdata attributes.

    The noscript element was a "block-level" element in HTML4, but is phrasing content in HTML.

    The table, thead, tbody, tfoot, tr, ol, ul and dl elements are allowed to be empty in HTML.

    Table elements have to conform to the table model (e.g. two cells are not allowed to overlap).

    The table element now does not allow col elements as direct children. However, the HTML parser implies a colgroup element, so this change should not affect text/html content.

    The table element now allows the tfoot element to be the last child.

    The caption element now allows flow content, but with no descendant table elements.

    The th element now allows flow content, but with no header, footer, sectioning content, or heading content descendants.

    The a element now has a transparent content model (except it does not allow interactive content descendants), meaning that it has the same content model as its parent. This means that the a element can now contain e.g. div elements, if its parent allows flow content.

    The ins and del elements also have a transparent content model. HTML4 had similar rules in prose that could not be expressed in the DTD.

    The object element also has a transparent content model, after its param children.

    The map element also has a transparent content model. The area element is considered phrasing content if there is a map element ancestor, which means that they do not need to be direct children of map.

    The fieldset element no longer requires a legend child.

    5 APIs

    HTML has introduced many new APIs and has extended, changed or obsoleted some existing APIs.

    5.1 New APIs

    HTML introduces a number of APIs that help in creating Web applications. These can be used together with the new elements introduced for applications:

    Media elements (video and audio) have APIs for controlling playback, syncronising multiple media elements, and timed text tracks (e.g. subtitles).

    An API for form constraint validation (e.g. the setCustomValidity() method).

    An API for commands that the user can invoke.

    An API that enables offline Web applications, with an application cache.

    An API that allows a Web application to register itself for certain protocols or media types, using registerProtocolHandler() and registerContentHandler().

    Editing API in combination with a new global contenteditable attribute.

    Drag & drop API in combination with a draggable attribute.

    An API that exposes the components of the document's URL and allows scripts to navigate, redirect and reload (the Location interface).

    An API that exposes the session history and allows scripts to update the document's URL without actually navigating, so that applications don't need to abuse the fragment component for "Ajax-style" navigation (the History interface).

    An API for base64 conversion (atob() and btoa() methods).

    An API to schedule timer-based callbacks (setTimeout() and setInterval()).

    An API to prompt the user (alert(), confirm(), prompt(), showModalDialog()).

    An API for printing the document (print()).

    An API for handling search providers (AddSearchProvider() and IsSearchProviderInstalled()).

    The Window, Navigator and External interfaces have been defined.

    An API for microdata.

    An API for immediate-mode bitmap graphics (the 2d context for the canvas element).

    An API for cross-document messaging, channel messaging and sending messages to other tabs in the same origin (postMessage(), MessageChannel and BroadcastChannel).

    An API for runnings scripts in the background (Worker and SharedWorker).

    An API for client-side storage (localStorage and sessionStorage).

    An API for bidirectional client-server communication (WebSocket).

    An API for server-to-client data push (EventSource).

    5.2 Changed APIs

    The following features from DOM Level 2 HTML are changed in various ways:

    document.title now collapses whitespace on getting.

    document.domain is made settable, which can change the document's effective script origin.

    document.open() now either clears the document (if invoked with two or less arguments), or acts like window.open() (if invoked with three or four arguments). In the former case, throws an exception in XML.

    document.close(), document.write() and document.writeln() throw an exception in XML. The latter two now support variadic arguments; they can add text to the document's input stream while it is still being parsed, imply a call to document.open(), or be ignored altogether in some cases.

    document.getElementsByName() now returns all HTML elements with a name attribute matching the argument.

    elements on HTMLFormElement now returns an HTMLFormControlsCollection of button, fieldset, input, keygen, object, output, select and textarea elements. length returns the number of nodes in elements.

    add() on HTMLSelectElement now also accepts an integer as its second argument.

    remove() on HTMLSelectElement now removes the first element in the collection if the argument is out of bounds.

    a and area elements now stringify to their href attribute.

    The click(), focus() and blur() methods are now available on all HTML elements.

    5.3 Extensions to Document

    DOM Level 2 HTML had an HTMLDocument interface that inherited from Document and provided HTML-specific members on documents. HTML has moved these members to the Document interface, and extended it in a number of ways. Since all documents use the Document interface, the HTML-specific members are now available on all documents, so they are usable in e.g. SVG documents as well. It also has several new members:

    location, lastModified and readyState to help resource metadata management.

    dir, head, embeds, plugins, scripts, commands, and a generic name getter, to access various parts of the DOM tree.

    getItems() for microdata.

    cssElementMap to accompany the CSS element() feature.

    currentScript which returns the currently running script element (or null).

    activeElement and hasFocus to determine which element is currently focused and whether the Document has focus respectively.

    designMode, execCommand(), queryCommandEnabled(), queryCommandIndeterm(), queryCommandState(), queryCommandSupported(), queryCommandValue() for the editing API.

    All event handler IDL attributes. Also, onreadystatechange is a special event handler IDL attribute that is only available on Document.

    Existing scripts that modified the prototype of HTMLDocument should continue to work because window.HTMLDocument now returns the Document interface object.

    5.4 Extensions to HTMLElement

    The HTMLElement interface has also gained several extensions in HTML:

    translate, hidden, tabIndex, accessKey, draggable, dropzone, contentEditable, contextMenu, spellcheck and style reflect content attributes.

    dataset is a convenience feature for handling the data-* attributes, which are exposed as camel-cased properties; for instance, elm.dataset.fooBar = 'test' sets the data-foo-bar content attribute on elm.

    itemScope, itemType, itemId, itemRef, itemProp, properties and itemValue for microdata.

    click(), focus() and blur() allow scripts to simulate clicks and moving focus.

    accessKeyLabel gives the shortcut key that the user agent has assigned for the element, which the Web developer can influence with the accesskey attribute.

    isContentEditable returns true if the element is editable.

    forceSpellCheck() causes the user agent to check spelling of an element.

    commandType, commandLabel, commandIcon, commandHidden, commandDisabled and commandChecked is part of the command API.

    All event handler IDL attributes.

    Some members were previously defined on HTMLElement but been moved to the Element interface in the DOM standard: [DOM]

    id reflects the id content attribute.

    className reflects the class content attribute.

    classList is a convenient accessor for className. The object it returns exposes methods (contains(), add(), remove(), and toggle()) for manipulating the element's classes.

    getElementsByClassName() returns a list of elements with the specified classes.

    5.5 Extensions to Other Interfaces

    Some interfaces in DOM Level 2 HTML have been extended.

    HTMLOptionsCollection now has a legacy caller, setter creator, and the members add(), remove() and selectedIndex

    HTMLLinkElement and HTMLStyleElement now implement the LinkStyle interface from CSSOM. [CSSOM]

    HTMLFormElement now has a named getter and an indexed getter, as well as the checkValidity(), reportValidity() and requestAutocomplete() methods.

    HTMLSelectElement now has a getter, item() and namedItem() methods, a setter creator, selectedOptions and labels IDL attributes, and members for the form constrain validation API: willValidate, validity, validationMessage, checkValidity(), reportValidity(), and setCustomValidity().

    HTMLOptionElement now has a constructor Option.

    HTMLInputElement now has the members files, height, indeterminate, list, valueAsDate, valueAsNumber, width, stepUp(), stepDown(), the form constraint validation API members, labels, and members for the text field selection API: selectionStart, selectionEnd, selectionDirection, setSelectionRange() and setRangeText().

    HTMLTextAreaElement now has the members textLength, the form constraint validation API members, labels and the text field selection API members.

    HTMLButtonElement now has the form constraint validation API members and labels.

    HTMLLabelElement now has the member control.

    HTMLFieldSetElement now has the members type, elements and the form constraint validation API members.

    HTMLAnchorElement now has the members relList, text, and implements the URLUtils interface which has the members href, origin, protocol, username, password, host, hostname, port, pathname, search, searchParams and hash. HTMLLinkElement and HTMLAreaElement also have the relList IDL attribute. HTMLAreaElement also implements the URLUtils interface.

    HTMLImageElement now has a constructor Image, and the members naturalWidth, naturalHeight and complete.

    HTMLObjectElement now has the members contentWindow, the form constraint validation API members and a legacy caller.

    HTMLMapElement now has the member images.

    HTMLTableElement now has the members createTBody() and stopSorting().

    HTMLTableHeaderCellElement now has the member sort().

    HTMLIFrameElement now has the member contentWindow.

    In addition, most new content attributes also have corresponding IDL attributes on the elements' interfaces, e.g. the sizes IDL attribute on HTMLLinkElement which reflects the sizes content attribute.

    5.6 Obsolete APIs

    Some APIs are now either removed altogether, or marked as obsolete.

    All IDL attributes that reflect a content attribute that is itself obsolete, are now also obsolete; for instance, the bgColor IDL attribute on HTMLBodyElement which reflects the obsolete bgcolor content attribute is now obsolete.

    The following interfaces are marked obsolete since the elements are obsolete: HTMLAppletElement, HTMLFrameSetElement, HTMLFrameElement, HTMLDirectoryElement and HTMLFontElement.

    The HTMLIsIndexElement interface is removed altogether since the HTML parser expands an isindex tag into other elements. The HTMLBaseFontElement interface is also removed since the element has no effect.

    The following members of the HTMLDocument interface (which have now moved to Document) are now obsolete: anchors and applets.

    Acknowledgments

    The editors would like to thank Ben Millard, Bruce Lawson, Cameron McCormack, Charles McCathieNevile, Dan Connolly, David Håsäther, Dennis German, Frank Ellermann, Frank Palinkas, 羽田野太巳 (Futomi Hatano), Gordon P. Hemsley, Henri Sivonen, Jacob Palme, James Graham, Jens Oliver Meiert, Jeremy Keith, Jukka K. Korpela, Jürgen Jeka, Krijn Hoetmer, Leif Halvard Silli, Maciej Stachowiak, Mallory van Achterberg, Marcos Caceres, Mark Pilgrim, Martijn Wargers, Martin Leese, Martyn Haigh, Masataka Yakura, Michael Smith, Mike Taylor, Ms2ger, Olivier Gendrin, Øistein E. Andersen, Philip Jägenstedt, Philip Taylor, Randy Peterman, Robin Berjon, Steve Faulkner, Timo Tijhof, Toby Inkster, Xaxio Brandish, Yngve Spjeld Landro and Zhong Yu for their contributions to this document as well as to all the people who have contributed to HTML over the years for improving the Web!

    References

    [CSSOM] CSS Object Model (CSSOM), Simon Pieters and Glenn Adams. W3C. [DOCTYPE] Activating Browser Modes with Doctype, Henri Sivonen. [DOM] DOM, Anne van Kesteren, Aryeh Gregor and Ms2ger. WHATWG. [DOM2HTML] Document Object Model (DOM) Level 2 HTML Specification, Johnny Stenback, Philippe Le Hégaret and Arnaud Le Hors. W3C. [HTML] HTML, Ian Hickson. WHATWG. [HTML4] HTML 4.01 Specification, Dave Raggett, Arnaud Le Hors and Ian Jacobs. W3C. [HTML5] HTML5, Robin Berjon, Steve Faulkner, Travis Leithead et al.. W3C. [HTML5NIGHTLY] HTML 5.1 Nightly, Robin Berjon, Steve Faulkner, Travis Leithead et al.. W3C. [XHTML1] XHTML™ 1.1 - Module-based XHTML - Second Edition, Murray Altheim and Shane McCarron. [XML] Extensible Markup Language, Tim Bray, Jean Paoli, C. M. Sperberg-McQueen et al.. W3C. [XMLNS] Namespaces in XML, Tim Bray, Dave Hollander, Andrew Layman et al.. W3C.

    转载请注明原文地址: https://ju.6miu.com/read-675332.html

    最新回复(0)