0

对不起愚蠢的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);
};
4

1 回答 1

4

getPropertyValue需要连字符大小写名称("margin-top"等,而不是"marginTop"等)。

但是您可以直接通过括号表示法使用样式对象:

console.log(constContentContainerStyles[tmpStylesArray[i]]);

支持 camelCase ( "marginTop") 和 hyphen-case ( "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>

于 2021-10-20T14:24:25.770 回答