jQuery幻灯片 [英] jQuery slideshow

查看:120
本文介绍了jQuery幻灯片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建自己的幻灯片.以下代码从一幅图像淡入另一幅图像.我想从img1.jpg循环到img4.jpg,但是我不确定每次更改后如何暂停.

I'm trying to create my own slideshow. The following code fades from one image to another. I'd like to cycle from img1.jpg to img4.jpg but i'm not sure how to pause after each change.

                i++;
                temp = "img"+i+".jpg";
                $("#img").fadeOut(function() {
                    $(this).load(function() { $(this).fadeIn(); });
                    $(this).attr("src", temp);
                });

更新:我将代码更改为以下代码.根据John Boker的建议,我将图像重命名为img0,img1,img2,img3.它转到刚刚停止的第一张,第二张,第三张图像.有什么想法吗?

UPDATE: I've changed the code to the following. On John Boker's advice i've renamed the images to img0, img1, img2, img3. It goes to the first, second, third image the just stops. Any ideas?

<html>
    <head>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
        <script>

            $(document).ready(function(){           
                var temp="";

                function slideshow(i)
                {
                    temp = "img"+i+".jpg";
                    $("#img").fadeOut(function() {
                         $(this).load(function() {
                                    $(this).fadeIn();
                                    // set a timeout of 5 seconds to show the next image;
                                    setTimeout(function(){ slideshow((i+1)%4); }, 5000);
                         });
                         $(this).attr("src", temp);
                    });
                }

                slideshow(0);


            });

        </script>
    </head>
    <body>
        <img src="img1.jpg" id="img"/>
    </body>
</html>

推荐答案

您可以使用 setInterval :

$(function() {

    var i = 0;

    // Four-second interval
    setInterval(function() {
        $("#img").fadeOut(function() {
            $(this).attr("src", "img" + i++ % 4 + ".jpg");
            $(this).fadeIn();
        });
    }, 4000);
}

我已经简化了一些可能导致您遇到的其他问题的事情,删除了fadeOut回调中对load的(看似多余的)调用,并消除了不必要的temp变量

I've simplified a few things that might have been causing some of the other problems you're seing, removing the (seemingly superfluous) call to load inside your fadeOut callback and eliminating the unnecessary temp variable.

(最后,如果您不只是为了学习而做,请考虑使用许多出色的幻灯片插件之一,例如 循环 .)

(Finally, if you aren't just doing this to learn, consider using one of the many excellent slideshow plugins out there, like Cycle.)

这篇关于jQuery幻灯片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆