我尝试制作一个图像滑块,在几秒钟内过渡到新图像。然而,由于某种原因,它不会在开始时回到图片,似乎试图尴尬地过渡。这里是代码其余部分https://codepen.io/anon/pen/YvPdNj
的链接var i = 0; //title
var size = 0 //image
var fade = 4000;
function imgTransition() {
var transit = document.getElementsByTagName("img")
for(var i= 0; i < transit.length - 1; i++) {
transit[size].style.opacity = 0;
}
if (size < transit.length - 1) {
size++;
transit[size].style.opacity = 1;
}
else {
size = 0;
transit[size].style.opacity = 1;
}
setInterval('imgTransition()', fade);
}
window.onload = function() {
imgTransition();
};
答案 0 :(得分:0)
以下是我对您的代码所做的一些更改:
我首先对global
变量进行了更改,因为我为图像索引添加了imgind
,为图像集合添加了transit
,然后我分配了transit
和{{1} size
事件中的变量,因此您不必在代码中一次又一次地分配它们,然后我在load
事件中调用函数titleTransition()
,因为它未被声明(您可以稍后使用)并将第一张图像的load
设置为1,因为它首先显示,然后调用opacity
而不是setInterval(imgTransition, fade);
,以便设置的间隔为sepearte代码而不是自称。
这里看一下这个修改过的片段:
<强>段强>
imgTransition()
var i = 0; //title
var imgind = 0;
var size = 0 //image
var time = 3000;
var fade = 4000;
var transit = null;
function imgTransition() {
transit[imgind].style.opacity = 0; //hiding the indexed image
imgind++; //incrementing the image index
if (imgind >= size) //checking if the index is greater then or equals to size
imgind = 0; //setting index to 1st image i.e 0.
transit[imgind].style.opacity = 1; //displaying the next image
}
window.onload = function() {
transit = document.getElementsByTagName("img"); // get the collection of images
size = transit.length; //get the size of images
transit[imgind].style.opacity = 1; //to set the opacity of 1st image
setInterval(imgTransition, fade);
//titleTransition(); //undefined funciton
};
img {
transition: all .5s ease-in;
left: 160px;
position: absolute;
width: 30%;
height: 50%;
margin: 0;
padding: 0;
opacity: 0;
}