如前一章所述,元素可以包含用於設置元素的各種屬性的屬性。
有些屬性是全局定義的,可以在任何元素上使用,而另一些屬性只爲特定元素定義。所有屬性都有一個名稱和一個值,如下例所示。
下面是一個HTML5屬性的例子,它演示了如何使用「example」−的值用一個名爲class的屬性標記div元素;
<div class = "example">...</div>
屬性只能在開始標記中指定,決不能在結束標記中使用。
HTML5屬性是不區分大小寫的,可以用全大寫或混合大小寫編寫,儘管最常見的約定是堅持使用小寫。
Standard Attributes
下面列出的屬性幾乎得到了所有HTML5標記的支持。
Attribute | Options | Function |
---|---|---|
accesskey | User Defined | Specifies a keyboard shortcut to access an element. |
align | right, left, center | Horizontally aligns tags |
background | URL | Places an background image behind an element |
bgcolor | numeric, hexidecimal, RGB values | Places a background color behind an element |
class | User Defined | Classifies an element for use with Cascading Style Sheets. |
contenteditable | true, false | Specifies if the user can edit the element's content or not. |
contextmenu | Menu id | Specifies the context menu for an element. |
data-XXXX | User Defined | Custom attributes. Authors of a HTML document can define their own attributes. Must start with "data-". |
draggable | true,false, auto | Specifies whether or not a user is allowed to drag an element. |
height | Numeric Value | Specifies the height of tables, images, or table cells. |
hidden | hidden | Specifies whether element should be visible or not. |
id | User Defined | Names an element for use with Cascading Style Sheets. |
item | List of elements | Used to group elements. |
itemprop | List of items | Used to group items. |
spellcheck | true, false | Specifies if the element must have it's spelling or grammar checked. |
style | CSS Style sheet | Specifies an inline style for an element. |
subject | User define id | Specifies the element's corresponding item. |
tabindex | Tab number | Specifies the tab order of an element. |
title | User Defined | "Pop-up" title for your elements. |
valign | top, middle, bottom | Vertically aligns tags within an HTML element. |
width | Numeric Value | Specifies the width of tables, images, or table cells. |
有關HTML5標記和相關屬性的完整列表,請查看我們對HTML5標記的引用。
Custom Attributes
HTML5中引入的一個新特性是添加自定義數據屬性。
自定義數據屬性以data-開頭,並將根據您的要求命名。下面是一個簡單的例子;
<div class = "example" data-subject = "physics" data-level = "complex"> ... </div>
上面的代碼將是完全有效的HTML5,有兩個自定義屬性,稱爲datasubject和data level。您將能夠使用JavaScript api或CSS以與獲取標準屬性類似的方式獲取這些屬性的值。