尝试通过JavaScript添加背景颜色到HTML元素

发布于 2025-02-09 14:53:55 字数 522 浏览 2 评论 0原文

因此,我有一个阵列,其中包含电影的标题和封面。我正在尝试使用封面图像作为背景图像在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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

感受沵的脚步 2025-02-16 14:53:55

您需要使用字符串插值来获取值。您也不能使用url值使用background-color,您应该使用background而不是:

div.style.background = `url(${moviesToDisplay[each]['cover']})`;

You need to use string interpolation to get the value. You also can't use url values with background-color, you should use background instead:

div.style.background = `url(${moviesToDisplay[each]['cover']})`;
寻梦旅人 2025-02-16 14:53:55
div.style.background = `url("${moviesToDisplay[each]['cover']}")`;

要将图像设置为背景,请设置backgroundImage背景属性。

另外,您将需要使用字符串插值,否则它将将背景图像设置为字符串。

另外,url()拿一个字符串,这就是为什么“”需要。

div.style.background = `url("${moviesToDisplay[each]['cover']}")`;

To set image as background, either set backgroundImage or background 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文