旋转木马前端实现
时间: 2023-06-29 18:20:49 浏览: 215
旋转木马是一种常见的前端 UI 效果,以下是一种实现方式:
1. HTML 结构
```html
<div class="carousel">
<div class="carousel-item active">
<img src="image1.jpg" alt="">
</div>
<div class="carousel-item">
<img src="image2.jpg" alt="">
</div>
<div class="carousel-item">
<img src="image3.jpg" alt="">
</div>
<div class="carousel-item">
<img src="image4.jpg" alt="">
</div>
</div>
```
2. CSS 样式
```css
.carousel {
position: relative;
width: 500px;
height: 300px;
margin: 0 auto;
perspective: 1000px;
}
.carousel-item {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
transition: transform 1s;
transform-origin: 50% 50% -300px;
box-shadow: 0 0 10px rgba(0,0,0,.3);
}
.carousel-item.active {
transform: rotateY(0deg);
z-index: 1;
}
.carousel-item.next {
transform: rotateY(-90deg);
z-index: 2;
}
.carousel-item.prev {
transform: rotateY(90deg);
z-index: 0;
}
.carousel-item.hidden {
transform: rotateY(180deg);
z-index: -1;
}
```
3. JavaScript 代码
```javascript
var carousel = document.querySelector('.carousel');
var carouselItems = document.querySelectorAll('.carousel-item');
var activeIndex = 0;
var prevIndex = carouselItems.length - 1;
var nextIndex = 1;
function setActiveIndex(index) {
activeIndex = index;
prevIndex = index === 0 ? carouselItems.length - 1 : index - 1;
nextIndex = index === carouselItems.length - 1 ? 0 : index + 1;
updateCarousel();
}
function updateCarousel() {
carouselItems.forEach(function(item, index) {
if (index === activeIndex) {
item.classList.add('active');
item.classList.remove('prev');
item.classList.remove('next');
item.classList.remove('hidden');
} else if (index === prevIndex) {
item.classList.add('prev');
item.classList.remove('active');
item.classList.remove('next');
item.classList.remove('hidden');
} else if (index === nextIndex) {
item.classList.add('next');
item.classList.remove('active');
item.classList.remove('prev');
item.classList.remove('hidden');
} else {
item.classList.add('hidden');
item.classList.remove('active');
item.classList.remove('prev');
item.classList.remove('next');
}
});
}
updateCarousel();
setInterval(function() {
setActiveIndex((activeIndex + 1) % carouselItems.length);
}, 3000);
```
通过 CSS 的 transform 和 transition 属性实现旋转效果,通过 JavaScript 控制三个元素(当前、前一个、后一个)的类名来实现切换效果。
阅读全文