javascript - 为什么 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 对象的样式属性。
为什么这不起作用?
解决方案
你拼错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>
推荐阅读
- firebase - 无法从 Firebase 检索文档
- python - 和使用字符串的语句不起作用(Python3)
- docker - DICOM 发送错误 - Horos 未将文件发送到 Orthanc docker 容器
- c - Isalpha 需要标识符
- html - Angular 8 - 通过动态扩展和折叠递归地实现分层列表
- mysql - 如何设置日期数据类型默认值 EMPTY?
- groovy - 在 Groovy 中生成 JSON 对象
- ros - 带有 vrep/scan 和 slam 的laser_scan_matcher 的 tos tf 设置
- flutter - 如何将 material.io Color Tool Palette 生成的方案导入 Flutter/Android Studio?
- jenkins - Jenkins 实例在 Centos 上出现离线