作为替代方案。如果您正在尝试制作滑块。
通常的方法是动画出帧并动画入帧。
这就是幻灯片效果和淡入淡出效果起作用的原因。您的示例逐渐消失。这很好,但一旦您看到它工作,可能不是您真正想要的。
如果你真正想要的是动画图像进出……你需要一些更复杂的东西。
要使图像进出动画,您必须为每个图像元素使用一个图像元素,然后翻转一个并翻转一个。如果要滑动,图像需要在淡入淡出的情况下彼此叠放你把它们放在一起。
然后您的幻灯片功能就会发挥作用,但在您执行此操作之前,您需要将数组中的所有图像添加到 dom 中,这称为动态 dom 注入,它真的很酷。
确保您检查小提琴以获取完整的工作演示和底部链接的代码。
HTML
<div id="slider">
// ...we will dynamically add your images here, we need element for each image
</div>
JS
var curIndex = 0,
imgDuration = 3000,
slider = document.getElementById("slider"),
slides = slider.childNodes; //get a hook on all child elements, this is live so anything we add will get listed
imgArray = [
'http://placehold.it/300x200',
'http://placehold.it/200x100',
'http://placehold.it/400x300'];
//
// Dynamically add each image frame into the dom;
//
function buildSlideShow(arr) {
for (i = 0; i < arr.length; i++) {
var img = document.createElement('img');
img.src = arr[i];
slider.appendChild(img);
}
// note the slides reference will now contain the images so we can access them
}
//
// Our slideshow function, we can call this and it flips the image instantly, once it is called it will roll
// our images at given interval [imgDuration];
//
function slideShow() {
function fadeIn(e) {
e.className = "fadeIn";
};
function fadeOut(e) {
e.className = "";
};
// first we start the existing image fading out;
fadeOut(slides[curIndex]);
// then we start the next image fading in, making sure if we are at the end we restart!
curIndex++;
if (curIndex == slides.length) {
curIndex = 0;
}
fadeIn(slides[curIndex]);
// now we are done we recall this function with a timer, simple.
setTimeout(function () {
slideShow();
}, imgDuration);
};
// first build the slider, then start it rolling!
buildSlideShow(imgArray);
slideShow();
小提琴:
http://jsfiddle.net/f8d1js04/2/