首页 > 解决方案 > 在 element.style 处附加宽度或高度,取决于数组值,纯 JS

问题描述

我正在尝试在我的 javascript 中添加widthheight动态添加到 element.style,因为这样我可以改变我的颜色叠加淡出的方式(从左到右或从下到上)。我这样做的方式是

let posArray = ['width', 'height']
let randInt = Math.round(Math.random())

如果我这样做会console.log(posArray[randInt])返回一个正确的宽度或高度字符串,因为 randInt 会生成一个介于 0 和 1 之间的数字。

但是,当我尝试这样做时,element.style.posArray[randInt] = '0';我只会遇到错误。

有没有办法解决这个问题?

提前致谢!

标签: javascript

解决方案


您的语法正在尝试访问posArrayelement.style 上的属性。你应该这样做:

const propertyName = posArray[randInt];
element.style[propertyName ] = '0';

推荐阅读