DOM 屬性項、屬性與樣式之間的處理有許多的細節,在實作中雖不以 JS 為主要影響成想的部分,但也可以在理解細節中學習瀏覽器處理這些樣式間的流程跟實作差異。
屬性項 style
屬性項 type
節點正規化名稱
kebab-case 到 camelCase 寫法
取得計算後樣式
style 屬性並不能抓到全部在 css style 處理完後的結果,只能初步得到 inline style 的結果。
<!DOCTYPE html>
<html lang="en-US">
<body style="font-weight:bold;">
<div style="color:red" id="myElement">..</div>
</body>
</html>
const element = document.getElementById("myElement");
let out = "";
const elementStyle = element.style;
const computedStyle = window.getComputedStyle(element, null);
for (const prop in elementStyle) {
if (Object.hasOwn(elementStyle, prop)) {
out += ` ${prop} = '${elementStyle[prop]}' > '${computedStyle[prop]}'\n`;
}
}
console.log(out);
<form id="testForm" action="/action_page.php">
<label for="fname">First name:</label><br>
<input type="number" id="fname" name="fname" value="John"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe"><br><br>
<input type="submit" value="Submit">
</form>
let input = document.querySelector("html #testForm input");
console.log(input.type); //number
var all = document.getElementsByTagName("*")[0];
for (var i = 0; i< all.length; i ++) {
var nodeName = all[i].nodeName.toLowerCase();
if(nodeName === "div" || nodeName === "ul") {
all[i].calssName = "found";
}
}
function style(element, name, value){
name = name.replace(/-([a-z])/ig, function(all, letter){
return letter.toUpperCase()
})
if(typeof value !== 'undefined'){
element.style[name] = value;
}
return element.style[name];
}
var div = document.querySelector("div")
style(div, 'font-size')
let green = document.querySelector(".w3-left.w3-btn")
let element = window.getComputedStyle(green)
element.getPropertyValue("background-color")
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style