js简单实现轮播图效果
以下是一个使用原生JavaScript实现的简单轮播图效果的示例代码:
HTML部分:
<div id="carousel">
<div class="slide" style="background: red;"></div>
<div class="slide" style="background: green;"></div>
<div class="slide" style="background: blue;"></div>
</div>
<button onclick="prevSlide()">Prev</button>
<button onclick="nextSlide()">Next</button>
CSS部分:
#carousel {
position: relative;
width: 300px;
height: 200px;
overflow: hidden;
}
.slide {
position: absolute;
width: 100%;
height: 100%;
transition: transform 0.5s ease;
}
JavaScript部分:
const carousel = document.getElementById('carousel');
const slides = document.querySelectorAll('.slide');
let currentSlide = 0;
const moveToSlide = (direction) => {
const slideWidth = carousel.offsetWidth;
slides[currentSlide].style.transform = `translateX(${direction * slideWidth}px)`;
};
const nextSlide = () => {
moveToSlide(-1);
currentSlide = (currentSlide + 1) % slides.length;
moveToSlide(0);
};
const prevSlide = () => {
moveToSlide(-1);
currentSlide = (currentSlide - 1 + slides.length) % slides.length;
moveToSlide(0);
};
这段代码实现了一个简单的轮播图效果。用户可以通过点击按钮来切换到上一张或下一张图片。轮播效果通过更改每张幻灯片的transform
属性来实现平滑过渡。currentSlide
变量用于跟踪当前显示的幻灯片索引。
评论已关闭