利用CSS3,设计实现多张图片的轮播。
时间: 2024-03-10 07:46:41 浏览: 152
好的,以下是一个利用CSS3实现的多张图片轮播的示例代码:
HTML代码:
```
<div class="slider">
<div class="slider-inner">
<img src="image1.jpg" alt="Image 1">
<img src="image2.jpg" alt="Image 2">
<img src="image3.jpg" alt="Image 3">
</div>
<div class="slider-nav">
<span class="slider-nav-item"></span>
<span class="slider-nav-item"></span>
<span class="slider-nav-item"></span>
</div>
</div>
```
CSS代码:
```
.slider {
position: relative;
width: 100%;
height: 400px;
overflow: hidden;
}
.slider-inner {
position: absolute;
top: 0;
left: 0;
width: 300%;
height: 100%;
display: flex;
transition: transform 0.5s ease-in-out;
}
.slider-inner img {
width: 33.333%;
height: 100%;
object-fit: cover;
}
.slider-nav {
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
display: flex;
}
.slider-nav-item {
width: 10px;
height: 10px;
margin-right: 10px;
border-radius: 50%;
background-color: #ccc;
cursor: pointer;
}
.slider-nav-item.active {
background-color: #333;
}
```
JavaScript代码:
```
const slider = document.querySelector('.slider');
const sliderInner = document.querySelector('.slider-inner');
const sliderNav = document.querySelector('.slider-nav');
const sliderNavItems = document.querySelectorAll('.slider-nav-item');
let currentSlide = 0;
function slideTo(slide) {
sliderInner.style.transform = `translateX(-${slide * 100}%)`;
sliderNavItems[currentSlide].classList.remove('active');
sliderNavItems[slide].classList.add('active');
currentSlide = slide;
}
sliderNav.addEventListener('click', e => {
const navItem = e.target.closest('.slider-nav-item');
if (!navItem) return;
const index = [...sliderNavItems].indexOf(navItem);
slideTo(index);
});
setInterval(() => {
const nextSlide = (currentSlide + 1) % sliderNavItems.length;
slideTo(nextSlide);
}, 5000);
```
这个轮播使用了CSS3的`transform`属性来实现滑动效果,使用了JavaScript来处理轮播的交互和自动轮播。另外,还添加了导航点来方便用户切换轮播图片。
阅读全文