Simple jquery photo slideshow

爷,独闯天下 提交于 2019-12-23 19:00:18

问题


I wanted to write my own slideshow script but the end result is it immediately jumps to image 6 and flashes (fades) violently... The HTML is just a page with an image id="ss1".

var i = 1;

$(document).ready(function(){
    slideShow();
});
var t;
function runSlideShow() {
    if(i >= 7) i = 1;
    $("#ss1").fadeTo("slow",0);
    document.getElementById('ss1').src = "img/" + i + ".jpg";
    $("#ss1").fadeTo("slow",1);
    i += 1;
    t = setTimeout(slideShow(), 5000);  
}

回答1:


I think the problem is that you use

t = setTimeout(slideShow(), 5000);

slideShow() immidiatly executes the slideShow() function again. Try replacing it with:

t = setTimeout('slideShow()', 5000);

instead. Be aware though that this uses eval, which is considered unsafe(not in this case though) and slow.

The fade isn't working because fade runs asynchronous in your code, meaning that it is fading in while it's fading out at the same time(which makes some weird situations happen obviously).

function runSlideShow() {
    if(i >= 7) i = 1;
    $("#ss1").fadeTo("slow",0, function() {
        document.getElementById('ss1').src = "img/" + i + ".jpg";
        $("#ss1").fadeTo("slow",1, function() {
            i += 1;
            t = setTimeout('slideShow()', 5000);
        });
    });  
}

should work. Since the code between the function() { } now will execute once the fade has finished.



来源:https://stackoverflow.com/questions/5010883/simple-jquery-photo-slideshow

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!