[英]Why aren't my images being updated as expected?
试图遵循我在这里找到的在我看来非常简单明了的指南:
但是在我的实现中它不起作用。 图像不会显示或更改。 任何提示?
编辑:与建议的副本不同。 现在 changeImage 后的括号已被删除,function 会重复,但不显示任何背景图像的问题仍然存在。
第二次编辑:我还尝试在 buildImage 之后删除括号,结果相同(不显示背景图像)
<div id="pupa">
</div>
<script>
var images = ['file:///Users/karin/PROJECTS/PORTFOLIO/pupal%20stage/img/stage12.jpg',
'file:///Users/karin/PROJECTS/PORTFOLIO/pupal%20stage/img/stage34.jpg',
'file:///Users/karin/PROJECTS/PORTFOLIO/pupal%20stage/img/stage56.jpg'];
var index = 0;
function buildImage() {
console.log("setting image");
document.getElementById('pupa').style.backgroundImage = 'url(' + images[index] + ')';
}
function changeImage() {
index++;
if (index >= images.length) index = 0;
console.log("changing image");
document.getElementById('pupa').style.backgroundImage = 'url(' + images[index] + ')';
}
buildImage();
setInterval(changeImage, 3000);
</script>
如果您将图像添加到 html 页面所在的同一文件夹中名为 img 的文件夹中,则此代码将起作用。
<html>
<head>
<style>
#pupa
{
width:300px;
height:300px;
background-position:center;
background-repeat:no-repeat;
background-size:cover;
}
</style>
</head>
<body>
<div id="pupa"></div>
<script>
var images = ['img/stage12.jpg',
'img/stage34.jpg',
'img/stage56.jpg'];
var index = 0;
document.getElementById('pupa').style.backgroundImage = `url(${images[index]})`;
setInterval(function(){
index=(++index >= images.length)?0:index;
console.log(`changing image of index : ${index}`);
document.getElementById('pupa').style.backgroundImage = `url(${images[index]})`;
},3000);
</script>
</body>
</html>
这是相同的代码,稍微调整了一下,你不需要另一个 function buildImage() 先设置图像,它可以工作(确保检查图像的路径)
确保根据需要更改宽度、高度、背景大小、图像名称、路径等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.