简体   繁体   English

如何使用element.style.backgroundImage =“ url(filePath)”将背景图像添加到javascript?

[英]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.

相关问题 Javascript element.style.backgroundImage无法加载图像 - Javascript element.style.backgroundImage not loading image element.style.backgroundImage = `url(${url})`; 不工作 - element.style.backgroundImage = `url(${url})`; not working 如何将样式元素添加到div并使用javascript将其删除 - How do I add a style element to a div and remove it using javascript 如何更改JavaScript数组中的backgroundImage url? - How do I change backgroundImage url in JavaScript array? 如何拉伸使用JS“ document.body.style.backgroundImage = url(imgsrc);”插入的背景图像? - How to stretch a background image thats being inserted with JS “document.body.style.backgroundImage = url(imgsrc);”? 如何使用 javascript 将图像添加到元素 - How do i add an image to an element using javascript javascript如何使用style属性查找哪些元素包含背景图像 - javascript how do i find which elements contain a background image using the style attribute 如何使用 JavaScript 获取元素的背景图片 URL? - How to get background image URL of an element using JavaScript? 想要使用JavaScript从CSS网址中获取图片,以便为背景图片设置样式 - Want to fetch image using javascript from css url so I can style the background image 如何获取特色图像并将其图像路径放入内联样式,即。 <div style=“background:url(filepath/here)”;> ? - How to get the featured image and put it's image path in to inline styles ie. <div style=“background:url(filepath/here)”;>?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM