我怎么能有mor图像?
<script>
var rotate = false;
function setbackground() {
newImage = rotate ?
'url(mimages/wallpaper2.jpg)' :
'url(mimages/shutterstock_105126044-795x380.jpg)';
rotate = !rotate;
document.getElementById('change').style.backgroundImage = newImage;
}
setInterval(setbackground, 4000);
</script>
我尝试添加相同的方式: 没用?
答案 0 :(得分:0)
您的网址也必须包含在报价中
newImage = rotate ? "url('mimages/wallpaper2.jpg')" : "url('mimages/shutterstock_105126044-795x380.jpg')";
答案 1 :(得分:0)
您应该创建变量newImage
。
将您的代码更新为:
var rotate = false;
function setbackground() {
var newImage = rotate ? 'url(mimages/wallpaper2.jpg)' : 'url(mimages/shutterstock_105126044-795x380.jpg)';
rotate = !rotate;
document.getElementById('change').style.backgroundImage = newImage;
}
setInterval(setbackground, 4000);
查看我的演示Here
更新了更多图片:
var images = [
"url(image.png)",
"url(image2.png)",
"url(image3.png)"
];
var index = 0;
var newImage = '';
function setbackground () {
newImage = images[index];
if (index !== images.length){
index++;
}
else {
index = 0;
}
document.getElementById('change').style.backgroundImage = newImage;
}
setInterval(setbackground, 4000);
答案 2 :(得分:0)
通过每次调用将更多动态图像名称(路径)传递给setbackground()函数。
答案 3 :(得分:0)
有几种方法可以解决这个问题。我建议将图像的url存储在一个数组中,并在每次后续调用setBackground()时递增一个计数器。
var images = [
"url('mimages/wallpaper2.jpg')",
"url('wallpaper2.jpg')",
"url('wallpaper3.jpg')"
];
var imageIndex = 0;
function setbackground() {
newImage = images[imageIndex];
document.getElementById('change').style.backgroundImage = newImage;
if (imageIndex != images.length){
imageIndex++;
}
else{
// If we've reached the end of the array, reset the index
imageIndex = 0;
}
document.getElementById('change').style.backgroundImage = newImage;
}
setInterval(setbackground, 4000);
如果要添加更多图像,只需在数组中添加新条目即可。