<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>跑马灯轮播图1</title>
<style type="text/css">
.slider {
width: 300px;
overflow: hidden;
position: relative;
}
.slides {
display: flex;
transition: transform 0.5s ease;
}
.slide {
flex: 0 0 100%;
}
button {
position: absolute;
top: 50%;
transform: translateY(-50%);
z-index: 2;
}
.prev {
left: 0;
}
.next {
right: 0;
}
</style>
</head>
<body>
<div class="slider">
<div class="slides">
<div class="slide">Slide 1</div>
<div class="slide">Slide 2</div>
<div class="slide">Slide 3</div>
</div>
<button class="prev">Prev</button>
<button class="next">Next</button>
</div>
<script>
const slider = document.querySelector('.slider');
const slides = document.querySelector('.slides');
const prevBtn = document.querySelector('.prev');
const nextBtn = document.querySelector('.next');
let slideIndex = 0;
nextBtn.addEventListener('click', () => {
slideIndex = (slideIndex + 1) % slides.children.length;
updateSlidePosition();
});
prevBtn.addEventListener('click', () => {
slideIndex = (slideIndex - 1 + slides.children.length) % slides.children.length;
updateSlidePosition();
});
function updateSlidePosition() {
slides.style.transform = `translateX(-${slideIndex * 100}%)`;
}
</script>
</body>
</html>
js实现循环切换滚动 按钮左右控制切换
最新推荐文章于 2024-07-16 17:26:59 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)