javascript - 在 element.style 处附加宽度或高度,取决于数组值,纯 JS
问题描述
我正在尝试在我的 javascript 中添加width
或height
动态添加到 element.style,因为这样我可以改变我的颜色叠加淡出的方式(从左到右或从下到上)。我这样做的方式是
let posArray = ['width', 'height']
let randInt = Math.round(Math.random())
如果我这样做会console.log(posArray[randInt])
返回一个正确的宽度或高度字符串,因为 randInt 会生成一个介于 0 和 1 之间的数字。
但是,当我尝试这样做时,element.style.posArray[randInt] = '0';
我只会遇到错误。
有没有办法解决这个问题?
提前致谢!
解决方案
您的语法正在尝试访问posArray
element.style 上的属性。你应该这样做:
const propertyName = posArray[randInt];
element.style[propertyName ] = '0';
推荐阅读
- python - 在python中,如何解析多层JSON?
- python - 蟒蛇 | MySQL | AttributeError:模块'mysql.connector'没有属性'connect'
- .net - VB NET 将值与列表中的值进行比较
- c - 为 char 数组实现 getLength-Function 时出现特定情况的奇怪错误
- javascript - iframe src 在按钮单击时更改
- python - 决定python进程允许的线程数的因素是什么?
- javascript - “尝试获取资源时出现网络错误。” 仅在火狐上
- alexa - Alexa Dialog Flow 问题 - 根据问题更改对话过程
- java - try and catch 语句没有给我任何结果?
- angular - 使用 Jasmine 返回 TypeError 的单元测试:this.changeDetectorReference.markForCheck 不是函数