data-*全域屬性構成一組稱作自訂 data 屬性的屬性。它能令 HTML 與其 DOM 擁有給腳本用的交換資訊。這種屬性設置的自訂資料,能透過元素的 HTMLElement
介面而活用。HTMLElement.dataset
property 允許訪問它們。*
可以是任何遵循以下規則的 xml 名稱:
- 名字絕對不能以
xml
起頭,無論是否用於 xml、 - 名字絕對不能包含分號(
U+003A
)、 - 名字絕對不能包含大寫
A
到大小Z
的拉丁字母。
請注意 HTMLElement.dataset
property 是個 DOMStringMap
,而自訂的 data 屬性名 data-test-value 因為所有的減號(U+002D
)都會被消去、緊接著的第一個字母,會被取代為駝峰式(camelcase)名字,所以要透過 HTMLElement.dataset.testValue
或 HTMLElement.dataset["testValue"]
訪問。
用法
藉由增加 data-* 屬性,即使是普通的 HTML 元素也能變成複雜而強大程式物件。例如說遊戲裡面的太空船精靈 能成為帶有 class 與數個 data-* 屬性的 <img>
元素:
<img class="spaceship cruiserX3" src="shipX3.png" data-ship-id="324" data-weapons="laserI laserII" data-shields="72%" data-x="414354" data-y="85160" data-z="31940" onclick="spaceships[this.dataset.shipId].blasted()" />
(參見這個網站)
規範
規範 | 狀態 | 註解 |
---|---|---|
HTML Living Standard The definition of 'data-*' in that specification. |
Living Standard | No change from latest snapshot, HTML 5.1 |
HTML 5.1 The definition of 'data-*' in that specification. |
Recommendation | Snapshot of HTML Living Standard, no change from HTML5 |
HTML5 The definition of 'data-*' in that specification. |
Recommendation | Snapshot of HTML Living Standard, initial definition. |
瀏覽器相容性
We're converting our compatibility data into a machine-readable JSON format.
This compatibility table still uses the old format,
because we haven't yet converted the data it contains.
Find out how you can help!
功能 | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
基本支援 | (Yes) | 6 (6) | (Yes) | (Yes) | (Yes) |
功能 | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|
基本支援 | (Yes) | 6.0 (6) | (Yes) | (Yes) | (Yes) | (Yes) |
參見
- 所有的全域屬性
- The
HTMLElement.dataset
property that allows to access and modify these values.