# HTML5 中的 data-* attribute 屬性 ~~~pug // HTML <div id="red" data-id="red"></div> <div id="green" data-id="green"></div> <div id="blue" data-id="blue"></div> ~~~ ~~~scss // css [data-id="red"] { color: red; } [data-id="green"] { color: green; } [data-id="blue"] { color: blue; } ~~~ ~~~javascript // javascript let el = document.querySelector("#red"); console.log(1, el.getAttribute("data-id")); //red // console.log(2, el.dataset.id) //red // console.log(3, document.querySelector("[data-id]")); //html // console.log(4, document.querySelectorAll('[data-id]')); ~~~ <style type="text/css"> #list { display: inline-block; font-family: Arial, Helvetica, sans-serif; } #list [data-id] { display: inline-block; margin: 5px; padding: 3px 5px; width: 50px; color: white; text-align: center; white-space: nowrap; } [data-id="red"] { background-color: red; } [data-id="red"]::before { content: attr(data-id); } [data-id="green"] { background-color: green; } [data-id="green"]::before { content: attr(data-id); } [data-id="blue"] { background-color: blue; } [data-id="blue"]::before { content: attr(data-id); } </style> <div id="list">demo: <div id="red" data-id="red"></div> <div id="green" data-id="green"></div> <div id="blue" data-id="blue"></div> </div> https://codesandbox.io/s/crazy-pond-6uldm5?file=/index.html ### 範例1. 賦予後台(CMS)控制樣式 https://codesandbox.io/s/html5-data-attribute-1-91bkbg ### 範例2. HTML控制後端API位置 https://codesandbox.io/s/html5-data-attribute-2-4vengm
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up