尝试通过JavaScript添加背景颜色到HTML元素
因此,我有一个阵列,其中包含电影的标题和封面。我正在尝试使用封面图像作为背景图像在Flexbox中显示名称。 我还试图这样写:document.div.style.backgroundColor =“ url(infoforthatday [every] ['cover'])”;
我的代码:
for(let each in moviesToDisplay) {
let div = document.createElement("div")
div.innerText = moviesToDisplay[each]['title'];
//That is where I'm trying to set the background color
div.style.backgroundColor = "url(moviesToDisplay[each]['cover'])";
flex.appendChild(div);
}
预先感谢您 祝你有美好的一天 ^_ ^
so I have an array, containing titles and covers for movies. I'm trying to display the names in the flexbox, using cover image as background image.
I also tried to write it like that: document.div.style.backgroundColor = "url(infoForThatDay[each]['cover'])";
but it didn't work either
Here is the snippet of my code:
for(let each in moviesToDisplay) {
let div = document.createElement("div")
div.innerText = moviesToDisplay[each]['title'];
//That is where I'm trying to set the background color
div.style.backgroundColor = "url(moviesToDisplay[each]['cover'])";
flex.appendChild(div);
}
Thank you in advance <3
have a great day ^_^
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要使用字符串插值来获取值。您也不能使用
url
值使用background-color
,您应该使用background
而不是:You need to use string interpolation to get the value. You also can't use
url
values withbackground-color
, you should usebackground
instead:要将图像设置为背景,请设置
backgroundImage
或背景
属性。另外,您将需要使用字符串插值,否则它将将背景图像设置为字符串。
另外,
url()
拿一个字符串,这就是为什么“”
需要。To set image as background, either set
backgroundImage
orbackground
property.Also, you will need to use string interpolation else it will set the background image to whatever the string is.
Also,
url()
takes a string, that's why""
are required.