【发布时间】:2016-03-05 16:39:39
【问题描述】:
我有这个幻灯片 JS 代码,它可以根据我们想要的时间在 div 中切换图像。但是,如何添加淡入/淡出效果而不是没有动画的基本过渡?我在没有 jQuery 的情况下这样做,只是普通的 javascript。这是链接:https://en.khanacademy.org/computer-programming/js-library-exatreojs-slideshow-library/2950604004
代码如下:
var slideShow = function(container, time) {
container = document.getElementById(container);
this.images = [];
this.curImage = 0;
for (i = 0; i < container.childElementCount; i++) {
this.images.push(container.children[i]);
this.images[i].style.display = "none";
}
// Handle going to to the next slide
var nextSlide = function() {
for (var i = 0; i < this.images.length; i++) {
this.images[i].style.display = "none";
}
this.images[this.curImage].style.display = "block";
this.curImage++;
if (this.curImage >= this.images.length) {
this.curImage = 0;
}
window.setTimeout(nextSlide.bind(document.getElementById(this)), time);
// old code: window.setTimeout(nextSlide.bind(this), time);
};
nextSlide.call(this);
};
slideShow("slideshow", 1000);
// old code: slideShow(document.getElementById("slideshow"), 1000);
<div id="slideshow">
<img src="https://www.kasandbox.org/programming-images/animals/birds_rainbow-lorakeets.png" alt="Rainbow lorakeets" />
<img src="https://www.kasandbox.org/programming-images/animals/butterfly.png" alt="Butterfly" />
<img src="https://www.kasandbox.org/programming-images/animals/cat.png" alt="Cat" />
<img src="https://www.kasandbox.org/programming-images/animals/crocodiles.png" alt="Crocodiles" />
<img src="https://www.kasandbox.org/programming-images/animals/fox.png" alt="Fox" />
</div>
【问题讨论】:
-
要添加淡入淡出,您需要使用从 0 到 1 的计时器逐渐增加新图像的不透明度。因此可能需要绝对定位两个图像,一个具有较低 z- index 正在被另一个具有更高 z-index 的图像替换,并且在此图像上将是不透明动画。
-
谢谢!让我走上正轨!
-
另外,您可能希望通过一个包含对实际代码的 setTimeout 调用的循环进行渐进淡入/淡出。在循环的每次迭代中, setTimeout 在调用执行淡入淡出的函数之前创建一个小的延迟。这样,不透明度的变化不会一下子发生。
标签: javascript html slideshow fading