jQuery实现两张图片渐入渐出无缝切
我们要实现的效果是:两张图片在同一个容器内,通过淡入淡出的方式进行无缝切换。即当一张图片淡出时,另一张图片同时淡入,整个过程流畅自然。
<div class="slider">
<img src="image1.jpg" alt="图片1">
<img src="image2.jpg" alt="图片2">
</div>
.slider {
position: relative;
overflow: hidden;
}
.slider img {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
opacity: 0;
transition: opacity 1s ease-in-o ut;
}
$(document).ready(function() {
var $images = $('.slider img');
var currentIndex = 0;
function showImage(index) {
$images.eq(index).fadeIn(1000).siblings().fadeOut(1000);
currentIndex = index;
}
// 自动播放
setInterval(function() {
currentIndex++;
if (currentIndex >= $images.length) {
currentIndex = 0;
}
showImage(currentIndex);
}, 3000);
});
slider
,包含两张图片。position: absolute
和 top: 0; left: 0;
使图片层叠。opacity: 0
,隐藏所有图片。transition
设置淡入淡出效果。showImage
,传入索引,使对应图片淡入,其他图片淡出。setInterval
实现自动播放。fadeIn
和 fadeOut
方法,同时控制两张图片的透明度,实现无缝切换。currentIndex
记录当前显示的图片索引,并通过模运算实现循环播放。fadeIn
和 fadeOut
的时间,以及 transition
的效果,来实现不同的过渡效果。animation
属性实现更复杂的动画效果。
<!DOCTYPE html>
<html>
<head>
<title>图片轮播</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
/* CSS样式同上 */
</style>
</head>
<body>
<div class="slider">
<img src="image1.jpg" alt="图片1">
<img src="image2.jpg" alt="图片2">
</div>
<script>
// JavaScript代码同上
</script>
</body>
</html>
通过以上代码,我们实现了简单的两张图片的渐入渐出无缝切换效果。你可以根据实际需求,添加更多的图片、自定义过渡效果、增加交互功能,打造出更加丰富的图片展示效果。
温馨提示:
transition
属性在目标浏览器中得到支持。想了解更多,可以提出以下问题:
欢迎提出你的想法!