实现淡入脚本

时间:2015-11-19 10:49:23

标签: jquery fadein

上次我做代码的时间是6年前,所以很遗憾我忘了很多。 我无法弄清楚如何在这个脚本中实现fade属性。

幻灯片正在播放,但我想让图片淡入而不是弹出。

var picPaths = ['images/home1.png', 'images/home2.png', 'images/home3.png', 'images/home4.png'];
var curPic = -1;
//preload the images for smooth animation
var imgO = new Array();
for (i = 0; i < picPaths.length; i++) {
    imgO[i] = new Image();
    imgO[i].src = picPaths[i];
}

function swapImage() {
    curPic = (++curPic > picPaths.length - 1) ? 0 : curPic;
    imgCont.src = imgO[curPic].src;
    setTimeout(swapImage, 3500);
}

window.onload = function () {
    imgCont = document.getElementById('content1');
    swapImage();
}

如果有人能告诉我把它放在哪里,如果你有时间...,我会非常感激。

如果您需要更多信息,请询问。

1 个答案:

答案 0 :(得分:0)

假设imgCont是一个全局变量,那么在swapImage我会调用

imgCont.fadeOut();

然后设置新图像

imgCont.src = imgO[curPic].src;

然后淡出

imgCont.fadeIn();

我创建了一个fiddle以显示正确的用法,因为后续行必须进入淡出内部的函数,以便在图像交换之前完成淡入淡出,然后在触发超时之前完成淡入淡出调用

更新:

你需要在你的页面上包含一个jquery包含(例如这个链接到jquery的在线cdn):

<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>

所以使用jquery和小提琴代码重写原始代码,

HTML中的

<img id="img_on_page" src="http://www.degraafschilderwerk.nl/wp-content/uploads/2015/10/houtsanering3.jpg"/>
<script>

中的

var picPaths = ['images/home1.png', 'images/home2.png', 'images/home3.png', 'images/home4.png'];
var currentPicIndex = 0;

$(function(){
   //this is the 'page load ready' function
   swapImage(); //this starts the swapping..
});

function swapImage(){
    $("#img_on_page").fadeOut(function(){
        //this code happens AFTER the fadeOut animation is done.
        currentPicIndex++;
        if( currentPicIndex > picPaths.length-1) currentPicIndex = 0; //loop images back to start when end of array reached.
        $("#img_on_page").prop("src", a[swap]);    
        $("#img_on_page").fadeIn(function(){
            //this code happens AFTER the fadeIn animation is done.
            setTimeout(swapImage, 2000);
        });
    });

}

我还使用此代码创建了更新的JSFiddle