javascript - jQuery 幻灯片

标签 javascript jquery image slideshow

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

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

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

<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 变量。

(最后,如果您这样做不仅仅是为了学习,请考虑使用众多优秀的幻灯片插件之一,例如 Cycle 。)

关于javascript - jQuery 幻灯片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2001770/

相关文章:

Javascript 限制将图像显示为 1 个显示器

javascript - 获取传递的数字参数并返回它的阶乘,例如 : if number is 4, 它应该返回 (4 * 3 * 2 * 1) 即 24

javascript - Foundation 5.2.3 顶部栏下拉不起作用

jquery - 如何使用 jQuery 在标题属性中显示链接文件的大小和类型?

html - 无法使用 Internet Explorer 拉伸(stretch)图像和覆盖纵横比

python - 使用 Python 从 Protobuf 解码图像

javascript - 使用 document.write 与逐个节点生成 dom 时的不同 CSS 继承

JavaScript 日期问题

javascript - 缺少绘图弹出窗口

javascript - 使用javascript禁用中间点击滚动