也许我做错了什么,但出于某种原因,如果我尝试使用模板字符串在 Javascript 中设置元素的样式属性,它就不起作用,而使用旧样式连接可以。例如,这有效:
containerAnim1.style.backgroundColor = 'rgb('
+ currentColor[0] + ', '
+ currentColor[1] + ', '
+ currentColor[2] + ')';
但出于某种原因,这不是:
containerAnim1.style.backgroundColor =
`rbg(${currentColor[0]}, ${currentColor[1]}, ${currentColor[2]})`;
我疯狂地试图找出我的代码出了什么问题,直到我发现 Chromium 和 Firefox 都不喜欢用于设置 DOM 对象样式属性的模板字符串。
为什么这不起作用?
最佳答案
你拼错了rgb
,你有rbg
。
const content = document.getElementById('content');
const currentColor1 = [255, 0, 0];
const currentColor2 = [0, 0, 0];
setTimeout(() => {
let s = 'rgb(' +
currentColor1[0] + ', ' +
currentColor1[1] + ', ' +
currentColor1[2] + ')';
console.log('regular:', s);
content.style.backgroundColor = s;
}, 1000);
setTimeout(() => {
let s = `rgb(${currentColor2[0]}, ${currentColor2[1]}, ${currentColor2[2]})`;
console.log('literal:', s);
content.style.backgroundColor = s;
}, 2000);
<div id="content" style="height: 200px; width: 200px; background: #eee;"></div>
关于javascript - 为什么 element.style.property 不适用于模板字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59228414/