首页 > 解决方案 > 如何使用 element.style.backgroundImage = "url(filePath)" 将背景图像添加到 javascript?

问题描述

我希望在 Javascript 中将背景图像添加到我的 HTML 中:

var filePath = 'randomImage.png'; 
card.style.backgroundImage = "url(filePath)"

DOM 结果:

div class="card" data-name="image" style="background-image: url("filePath");"

并且没有显示实际图像。

我知道可以通过硬编码 url('random-image.png'); 但这不是我想要的功能,因为 filePath 是动态的并且会随着时间而变化。

标签: javascripthtmlcssbackground-image

解决方案


因为 filePath 在引号中,所以它是按字面意思输入的,而不是从变量 filePath 中获取值。您可以通过像这样将变量添加到字符串中来解决此问题

card.style.backgroundImage = "url(" + filePath + ")";

或者如果你更喜欢这种语法,像这样。

card.style.backgroundImage = `url(${filePath})`;

希望这可以帮助!


推荐阅读