我正在一个动物救援的网站上工作,我正试图将一些动物的自动幻灯片放映,但是,对于我的生活,我无法让代码工作。有什么建议吗?
<div class="photobanner" style="max-height:460px">
<img class="myslides" src="image-1.jpg" style="height:100%" />
<img class="myslides" src="image-2.jpg" style="height:100%" />
<img class="myslides" src="image-3.jpg" style="height:100%" />
<img class="myslides" src="image-4.jpg" style="height:100%" />
<img class="myslides" src="image-5.jpg" style="height:100%" />
<img class="myslides" src="image-6.jpg" style="height:100%" />
</div>
<script type="text/javascript">
var myIndex = 0;
carousel();
function carousel() {
var i;
var x = document.getElementsByClassName("mySlides");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
myIndex++;
if (myIndex > x.length) {myIndex = 1}
x[myIndex-1].style.display = "block";
setTimeout(carousel, 2000); // Change image every 2 seconds
}
</script>
答案 0 :(得分:2)
试试这个小提琴:https://jsfiddle.net/zaedmfLs/
var myIndex = 0;
setInterval(carousel, 2000);
function carousel() {
var i;
var x = document.getElementsByClassName("myslides");
for (i = 0; i < x.length; i++) {
console.log("Carousel");
x[i].style.display = "none";
}
myIndex++;
if (myIndex > x.length) {myIndex = 1}
x[myIndex-1].style.display = "block";
}
您的代码几乎没有变化:
myslides
名称中有拼写错误(上限&#39; S&#39;)答案 1 :(得分:0)
您有两个主要问题:
mySlides
和myslides
不是一回事setTimeout
我会使用setInterval每2秒调用一次函数这是一个建议
var myIndex = 0;
var images = document.getElementsByClassName("myslides");
setInterval(carousel, 2000); // Change image every 2 seconds
function carousel() {
images[myIndex].style.display = "none";
myIndex++;
if (myIndex >= images.length) {
myIndex = 0;
}
console.log(myIndex, images.length);
images[myIndex].style.display = "block";
}
img.myslides {
display: None;
}
<div class="photobanner" style="max-height:460px">
<img class="myslides" src="image-1.jpg" style="height:100%" />
<img class="myslides" src="image-2.jpg" style="height:100%" />
<img class="myslides" src="image-3.jpg" style="height:100%" />
<img class="myslides" src="image-4.jpg" style="height:100%" />
<img class="myslides" src="image-5.jpg" style="height:100%" />
<img class="myslides" src="image-6.jpg" style="height:100%" />
</div>