gpt4 book ai didi

javascript - jQuery 幻灯片

转载 作者:行者123 更新时间:2023-11-28 12:50:09 28 4
gpt4 key购买 nike

我正在尝试创建自己的幻灯片。以下代码从一张图像淡入另一张图像。我想从 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com