gpt4 book ai didi

javascript - 动画 : jQuery vs CSS?

转载 作者:行者123 更新时间:2023-11-28 16:45:35 24 4
gpt4 key购买 nike

我一直在构建一个自定义 jQuery“旋转木马”( slider ),它会连续迭代三个图像。到目前为止,一切正常,但是我在尝试编写更改“#slideshow”的“src”属性同时触发淡入或淡出的代码时遇到了麻烦。

我的问题:我是否正确地解决了这个问题(使用 jQuery)或者我应该求助于切换 css 动画?

代码:

$(function() {

var slides = ['img/slide1.jpg', 'img/slide2.jpg', 'img/slide3.jpg'];

function changeSlide(arr) {
$('#slideshow').attr('src', arr[0]);
var i = 1;
setInterval(function() {
$('#slideshow').attr('src', arr[i]);
i++;
if (i >= arr.length) {
i = 0;
}
}, 3500);
}
changeSlide(slides);
});

为清楚起见,轮播的 HTML 如下所示:

<div id="carousel">
<img id="slideshow" src="img/slide1.jpg">
</div>

最佳答案

尝试加载所有图像以避免连续请求图像,将 class 设置为 slideshow 代替 id ,利用 complete .fadeIn() 的回调函数,.fadeOut() 在父元素中的第一张图像,在回调中的下一张图像

$(function() {
function changeSlide(el) {
$(el)
.fadeIn(1500, function() {
$(this).fadeOut(1500, function() {
changeSlide(this.nextElementSibling || this.parentElement.firstElementChild)
})
})
}
changeSlide($(".slideshow:first"));
});
.slideshow {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div id="carousel">
<img class="slideshow" src="http://lorempixel.com/50/50/nature" />
<img class="slideshow" src="http://lorempixel.com/50/50/sports" />
<img class="slideshow" src="http://lorempixel.com/50/50/cats" />
</div>

关于javascript - 动画 : jQuery vs CSS?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33228070/

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