请写个带时间轴轮播图
时间: 2024-02-27 16:54:27 浏览: 11
好的,以下是一个带时间轴的轮播图示例:
HTML 代码:
```html
<div class="slider">
<div class="slides">
<div class="slide" data-time="2022-01-01 00:00:00">
<img src="img/slide1.jpg" alt="">
<div class="caption">2022年元旦</div>
</div>
<div class="slide" data-time="2022-02-14 00:00:00">
<img src="img/slide2.jpg" alt="">
<div class="caption">情人节</div>
</div>
<div class="slide" data-time="2022-04-05 00:00:00">
<img src="img/slide3.jpg" alt="">
<div class="caption">清明节</div>
</div>
</div>
<div class="timeline">
<div class="progress"></div>
</div>
</div>
```
CSS 代码:
```css
.slider {
position: relative;
overflow: hidden;
width: 100%;
height: 400px;
}
.slides {
position: relative;
display: flex;
width: 300%;
height: 100%;
}
.slide {
position: absolute;
top: 0;
left: 0;
width: 33.33%;
height: 100%;
opacity: 0;
transition: opacity 1s ease-in-out;
}
.slide.active {
opacity: 1;
}
.slide img {
width: 100%;
height: 100%;
object-fit: cover;
}
.caption {
position: absolute;
bottom: 0;
left: 0;
padding: 10px;
background-color: rgba(0, 0, 0, 0.5);
color: #fff;
font-size: 18px;
}
.timeline {
position: absolute;
bottom: 0;
left: 0;
width: 100%;
height: 20px;
background-color: #eee;
z-index: 1;
}
.progress {
position: absolute;
top: 0;
left: 0;
width: 0;
height: 100%;
background-color: #333;
z-index: 2;
transition: width 1s linear;
}
```
jQuery 代码:
```js
$(document).ready(function() {
// 初始化轮播图
var slideIndex = 0;
var slides = $(".slide");
var progress = $(".progress");
var timelineWidth = $(".timeline").width();
showSlide(slideIndex);
// 自动轮播
setInterval(function() {
slideIndex++;
showSlide(slideIndex);
}, 3000);
// 显示轮播图
function showSlide(index) {
if (index >= slides.length) {
slideIndex = 0;
} else if (index < 0) {
slideIndex = slides.length - 1;
}
slides.removeClass("active");
$(slides[slideIndex]).addClass("active");
var time = $(slides[slideIndex]).data("time");
var duration = getTimeDuration(time);
progress.stop().animate({ width: "100%" }, duration, function() {
progress.css("width", 0);
showSlide(slideIndex + 1);
});
}
// 计算时间差
function getTimeDuration(time) {
var target = new Date(time).getTime();
var current = new Date().getTime();
return target - current;
}
});
```
该示例中,轮播图的容器为 `.slider`,包含一个图片列表 `.slides` 和一个时间轴 `.timeline`。每个图片元素都有一个 `data-time` 属性,表示图片的显示时间。使用 CSS 将图片元素设置为绝对定位,并且在当前显示的图片元素添加 `active` 类。使用 jQuery 实现自动轮播和时间轴的动画效果。在每次切换图片时,计算当前图片的显示时间与当前时间的时间差,将时间差作为动画的持续时间,并在时间轴上显示动画效果。