纯css实现轮播效果完整代码
时间: 2024-11-26 12:05:13 浏览: 19
纯 CSS 实现轮播效果通常不涉及复杂的 JavaScript 或 jQuery,而是利用 CSS 的关键帧动画(@keyframes)以及一些基本的 HTML 结构。这里是一个简单的例子,假设我们有三个图片容器,使用 `transform` 和 `transition` 属性创建平移切换的效果:
HTML:
```html
<div class="carousel">
<div class="slide" style="background-image: url(img1.jpg);">
<button class="prev">«</button>
<button class="next">»</button>
</div>
<div class="slide active" style="background-image: url(img2.jpg);"></div>
<div class="slide" style="background-image: url(img3.jpg);">
<button class="prev">«</button>
<button class="next">»</button>
</div>
</div>
```
CSS:
```css
.carousel {
position: relative;
width: 100%;
}
.slide {
position: absolute;
top: 0;
left: 0;
display: none;
width: 100%;
height: 400px; /* 你可以自定义高度 */
transition: transform 0.6s ease-in-out;
}
.slide.active {
display: block;
}
.carousel button {
position: absolute;
bottom: 10px;
right: 10px;
}
.prev {
content: " ";
background: transparent url(prev.svg) no-repeat center center;
}
.next {
content: " ";
background: transparent url(next.svg) no-repeat center center;
}
@keyframes carousel-slide {
0% { transform: translateX(0); }
50% { transform: translateX(-100%); }
100% { transform: translateX(0); }
}
```
JavaScript (用于添加按钮点击事件):
```javascript
const slides = document.querySelectorAll('.slide');
let index = 0;
function slide(index) {
slides.forEach(slide => slide.classList.remove('active'));
slides[index].classList.add('active');
}
['prev', 'next'].forEach(direction => {
const button = document.querySelector(`.${direction}`);
button.addEventListener('click', () => {
if (direction === 'prev') index--;
else index++;
index = Math.max(0, Math.min(index, slides.length - 1));
slide(index);
});
});
slide(index);
```
阅读全文