javascript - 为什么 element.style.property 不适用于模板字符串?

标签 javascript css dom

也许我做错了什么,但出于某种原因,如果我尝试使用模板字符串在 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/

相关文章:

javascript - 如何从 slider 的 DOM 中获取元素

javascript - 如何使用 javascript 枚举所有自定义 HTML 标签?

JavaScript:将子项附加到元素

javascript - 在 Canvas 上在线绘制另一个边框

css - 使用 line-height < 1 会导致问题吗?

css - 将输入 [提交] 与文本字段对齐

css - 文本渲染在 IE 上被 "gradient"搞砸了

javascript - jquery中的onClick事件

javascript - fs.writeFileSync 为错误 :UNKNOWN, 提供了在 nodejs 中进行同步文件写入的正确方法

javascript - 网站用键盘变成横向