[英]How do I add a background image to javascript using element.style.backgroundImage = “url(filePath)”?
I wish to add a background image into my HTML in Javascript: 我希望将背景图像添加到我的Javascript HTML中:
var filePath = 'randomImage.png';
card.style.backgroundImage = "url(filePath)"
The DOM result: DOM结果:
div class="card" data-name="image" style="background-image: url("filePath");"
And the actual image is not shown. 并且未显示实际图像。
I know that it can be done by hard-coding url('random-image.png'); 我知道可以通过对url('random-image.png')进行硬编码来完成; but this is not the functionality that I want because filePath is dynamic and changes over time.
但这不是我想要的功能,因为filePath是动态的并且随时间变化。
Because filePath is in quotations it's put in literally instead of getting the value from the variable filePath. 因为filePath用引号引起来,所以它按字面意义放置,而不是从变量filePath中获取值。 You can get around this by adding the variable onto the string like this
您可以通过将变量添加到字符串上来解决此问题
card.style.backgroundImage = "url(" + filePath + ")";
or if you prefer this syntax, like this. 或者,如果您喜欢这种语法,就这样。
card.style.backgroundImage = `url(${filePath})`;
Hope this helps! 希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.