使用 getComputedStyle() 遍历一组特定属性
Iterating through an array of specific properties using getComputedStyle()
抱歉这个愚蠢的 101 问题。我不确定为什么这不起作用。我正在尝试遍历使用 getComputedStyle()
返回的各种边距属性
任何帮助将不胜感激提前致谢 - CES
const constContentContainerStyles = window.getComputedStyle(constHTMLContentContainer);
let tmpStylesArray = ["marginTop", "marginLeft", "marginBottom", "marginRight"];
let x = 0;
for (let i = 0; i < tmpStylesArray.length; i++) {
//This throws undefined error
// x = constContentContainerStyles.tmpStylesArray[i];
//This returns 0
x = constContentContainerStyles.getPropertyValue(tmpStylesArray[i]);
console.log(tmpStylesArray[i] + " - " + x);
// returns the correct value
console.log(constContentContainerStyles.marginTop);
};
getPropertyValue
需要连字符大小写的名称("margin-top"
等,而不是 "marginTop"
等)。
但是您可以直接通过括号表示法使用样式对象:
console.log(constContentContainerStyles[tmpStylesArray[i]]);
支持驼峰式 ("marginTop"
) 和连字符式 ("margin-top"
):
const constHTMLContentContainer = document.getElementById("target");
const constContentContainerStyles = window.getComputedStyle(constHTMLContentContainer);
const tmpStylesArray = [
"marginTop",
"margin-top", // Added this to show it works too
"marginLeft",
"marginBottom",
"marginRight"
];
for (const name of tmpStylesArray) {
const x = constContentContainerStyles[name];
const note = name.includes("-") ? "Hyphen case works too: " : "";
console.log(`${note}${name} = ${x}`);
}
#target {
margin: 10px 20px 30px 40px;
}
<div id="target">x</div>
抱歉这个愚蠢的 101 问题。我不确定为什么这不起作用。我正在尝试遍历使用 getComputedStyle()
返回的各种边距属性任何帮助将不胜感激提前致谢 - CES
const constContentContainerStyles = window.getComputedStyle(constHTMLContentContainer);
let tmpStylesArray = ["marginTop", "marginLeft", "marginBottom", "marginRight"];
let x = 0;
for (let i = 0; i < tmpStylesArray.length; i++) {
//This throws undefined error
// x = constContentContainerStyles.tmpStylesArray[i];
//This returns 0
x = constContentContainerStyles.getPropertyValue(tmpStylesArray[i]);
console.log(tmpStylesArray[i] + " - " + x);
// returns the correct value
console.log(constContentContainerStyles.marginTop);
};
getPropertyValue
需要连字符大小写的名称("margin-top"
等,而不是 "marginTop"
等)。
但是您可以直接通过括号表示法使用样式对象:
console.log(constContentContainerStyles[tmpStylesArray[i]]);
支持驼峰式 ("marginTop"
) 和连字符式 ("margin-top"
):
const constHTMLContentContainer = document.getElementById("target");
const constContentContainerStyles = window.getComputedStyle(constHTMLContentContainer);
const tmpStylesArray = [
"marginTop",
"margin-top", // Added this to show it works too
"marginLeft",
"marginBottom",
"marginRight"
];
for (const name of tmpStylesArray) {
const x = constContentContainerStyles[name];
const note = name.includes("-") ? "Hyphen case works too: " : "";
console.log(`${note}${name} = ${x}`);
}
#target {
margin: 10px 20px 30px 40px;
}
<div id="target">x</div>