我想用 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 是动态的并且会随时间变化。
最佳答案
因为 filePath 在引号中,所以它是按字面意思放入的,而不是从变量 filePath 中获取值。您可以像这样将变量添加到字符串中来解决这个问题
card.style.backgroundImage = "url(" + filePath + ")";
或者如果您更喜欢这种语法,就像这样。
card.style.backgroundImage = `url(${filePath})`;
希望这对您有所帮助!
关于javascript - 如何使用 element.style.backgroundImage = "url(filePath)"将背景图像添加到 javascript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56544518/