web轮播图左右滑动代码
时间: 2024-11-30 13:16:50 浏览: 31
Web轮播图的左右滑动通常使用JavaScript库如Swiper、Bootstrap Carousel或者是原生的HTML5和CSS3结合实现。这里是一个简单的示例,使用纯JavaScript和HTML来创建一个基本的左右滑动轮播图:
```html
<!DOCTYPE html>
<html lang="zh">
<head>
<style>
.carousel {
width: 400px;
overflow: hidden;
}
.slide {
float: left;
transition: transform 0.6s ease;
}
</style>
</head>
<body>
<div class="carousel" id="myCarousel">
<div class="slide active">Slide 1</div>
<div class="slide">Slide 2</div>
<div class="slide">Slide 3</div>
</div>
<script>
const slides = document.querySelectorAll('.slide');
let currentSlideIndex = 0;
function slideRight() {
slides[currentSlideIndex].style.transform = 'translateX(-100%)';
currentSlideIndex = (currentSlideIndex + 1) % slides.length;
slides[currentSlideIndex].style.transform = 'translateX(0)';
}
function slideLeft() {
slides[currentSlideIndex].style.transform = 'translateX(100%)';
currentSlideIndex = (currentSlideIndex - 1 + slides.length) % slides.length;
slides[currentSlideIndex].style.transform = 'translateX(0)';
}
// 自动切换按钮
document.addEventListener('click', function(e) {
if (e.target.classList.contains('prev')) {
slideLeft();
} else if (e.target.classList.contains('next')) {
slideRight();
}
});
// 鼠标悬停切换效果
slides.forEach(function(slide, index) {
slide.addEventListener('mouseover', function() {
slide.style.transform = 'translateX(0)';
});
slide.addEventListener('mouseout', function() {
if (index === currentSlideIndex) return;
slides[index].style.transform = 'translateX(' + ((index > currentSlideIndex) ? '-100%' : '100%') + ')';
});
});
</script>
<!-- 左右箭头按钮 -->
<button class="prev"><</button>
<button class="next">></button>
</body>
</html>
```
在这个例子中,我们有三个`.slide`元素代表轮播图片,通过点击左右箭头按钮或鼠标悬停实现滑动效果。
阅读全文