从 JavaScript 中的单独文件夹中获取图像



我有一个有三个jpg的图像数组。我正在从图像数组设置类图片的背景图像。

我的问题是我已将图像放在具有URLimages/的图像文件夹中。 我想在行中添加images/

document.getElementById('content').style.backgroundImage = 'url('+images[index]+')';

怎么做?

var images = ['bus.jpg','car.jpg','scooter.jpg' ];
var index = 0;
function buildImage() {
document.getElementById('content').style.backgroundImage = 'url('+images[index]+')';
}
function changeImage() {
index++;
if (index >= images.length) index = 0;
document.getElementById('content').style.backgroundImage = 'url('+ images[index] + ')';
}
<div class="pic" id="content" >

您可以简单地连接文件夹路径。

var images = ['bus.jpg','car.jpg','scooter.jpg' ];
var index = 0;
var FolderPath="Images/";
function buildImage() {
document.getElementById('content').style.backgroundImage = 'url('+FolderPath+images[index]+')';
}
function changeImage() {
index++;
if (index >= images.length) index = 0;
document.getElementById('content').style.backgroundImage = 'url('+FolderPath+ images[index] + ')';
}

如果你对路径非常确定,你可以按如下方式使用它。

document.getElementById('content').style.backgroundImage = 'url('+ FolderPath + images[index] + ')';

最新更新