使用getComputedStyle()遍历指定margin属性数组时取值异常问题
问题原因
- 点语法返回undefined的原因
JS对象的点语法会将后续字段作为固定属性名解析,constContentContainerStyles.tmpStylesArray[i]实际是尝试读取constContentContainerStyles上名为tmpStylesArray的属性,再对该属性取下标i。而getComputedStyle返回的CSSStyleDeclaration对象不存在tmpStylesArray属性,因此返回undefined。动态读取对象属性必须使用方括号语法。 getPropertyValue返回0的原因getPropertyValue方法接收的参数是CSS原生短横线分隔(kebab-case)格式的属性名,而非JS中使用的驼峰(camelCase)格式。你传入的marginTop等驼峰命名无法匹配到对应的CSS属性,因此返回默认值0。
解决方案
方案1:使用方括号动态读取属性
无需修改现有数组的驼峰命名,直接用方括号语法读取动态属性即可,是最简便的实现方式。
修正后代码:
const constContentContainerStyles = window.getComputedStyle(constHTMLContentContainer); let tmpStylesArray = ["marginTop", "marginLeft", "marginBottom", "marginRight"]; let x = 0; for (let i = 0; i < tmpStylesArray.length; i++) { // 改用方括号读取动态属性 x = constContentContainerStyles[tmpStylesArray[i]]; console.log(tmpStylesArray[i] + " - " + x); }
方案2:适配getPropertyValue参数规则
将数组内的属性名改为短横线分隔的CSS原生命名,再调用getPropertyValue即可获取正确值。
修正后代码:
const constContentContainerStyles = window.getComputedStyle(constHTMLContentContainer); // 数组改为CSS短横线命名格式 let tmpStylesArray = ["margin-top", "margin-left", "margin-bottom", "margin-right"]; let x = 0; for (let i = 0; i < tmpStylesArray.length; i++) { x = constContentContainerStyles.getPropertyValue(tmpStylesArray[i]); console.log(tmpStylesArray[i] + " - " + x); }
内容的提问来源于stack exchange,提问作者CES
相关产品推荐
相关产品推荐

