为什么element.style.property无法与模板字符串一起使用?

时间:2019-12-07 17:13:07

标签: javascript css dom

也许我做错了事,但是由于某些原因,如果我尝试使用模板字符串在Javascript中设置元素的style属性,那将是行不通的,而使用旧样式串联则可以。例如,这有效:

    containerAnim1.style.backgroundColor = 'rgb('
      + currentColor[0] + ', '
      + currentColor[1] + ', '
      + currentColor[2] + ')';

但是由于某些原因,它没有:

    containerAnim1.style.backgroundColor = 
      `rbg(${currentColor[0]}, ${currentColor[1]}, ${currentColor[2]})`;

我一直想找出我的代码出了什么问题,直到发现Chromium和Firefox都不喜欢用于设置DOM对象样式属性的模板字符串后,我发疯了。

为什么这不起作用?

1 个答案:

答案 0 :(得分:1)

您拼写错误的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>