javascript - 如何使用 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 是动态的并且会随着时间而变化。
解决方案
因为 filePath 在引号中,所以它是按字面意思输入的,而不是从变量 filePath 中获取值。您可以通过像这样将变量添加到字符串中来解决此问题
card.style.backgroundImage = "url(" + filePath + ")";
或者如果你更喜欢这种语法,像这样。
card.style.backgroundImage = `url(${filePath})`;
希望这可以帮助!
推荐阅读
- php - Cake PHP 中前缀控制器中的 Flash 管理
- php - Laravel 日期列上的条件具有日期范围字符串
- html - 如何在 React 中根据视口修改 HTML
- android - 颤振:requestCode 只能使用低 16 位
- python - Pandas:重新采样分类索引数据
- reactjs - 为什么 Redux-Toolkit 切片中没有调用我的操作
- swift - ForEach 中的 SwiftUI 按钮不会改变 foregroundColor
- python-3.x - Python:Tkinter 聊天应用程序 - 我想在消息周围画气泡
- android - 使用 eclipse 2020-09 创建 android 项目会导致错误的包树
- powershell - Powershell脚本不返回日文字符而是随机数字和字母