首页 > 解决方案 > 为什么 element.style.property 不适用于模板字符串?

问题描述

也许我做错了什么,但由于某种原因,如果我尝试使用模板字符串在 Javascript 中设置元素的样式属性,它就不起作用,而使用旧样式连接则有效。例如,这有效:

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

但这出于某种原因不会:

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

我疯狂地试图弄清楚我的代码出了什么问题,直到我发现 Chromium 和 Firefox 都不喜欢模板字符串来设置 DOM 对象的样式属性。

为什么这不起作用?

标签: javascriptcssdom

解决方案


你拼错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>


推荐阅读