帮我完成移动端轮播图
时间: 2024-06-21 12:03:11 浏览: 13
移动端轮播图可以使用原生JS和CSS3来实现。下面提供一个例子[^1],帮助你完成移动端轮播图:
1. HTML结构
```html
<div class="container">
<div class="img-box">
<img src="1.jpg" alt="">
<img src="2.jpg" alt="">
<img src="3.jpg" alt="">
<img src="4.jpg" alt="">
</div>
<div class="dot-box">
<span></span>
<span></span>
<span></span>
<span></span>
</div>
</div>
```
2. CSS样式
```css
.container {
width: 100%;
overflow: hidden;
position: relative;
}
.img-box {
display: flex;
width: 400%;
transition: all .5s;
}
.img-box img {
width: 25%;
}
.dot-box {
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
}
.dot-box span {
display: inline-block;
width: 10px;
height: 10px;
border-radius: 50%;
margin: 0 5px;
background-color: #fff;
opacity: .5;
cursor: pointer;
}
.dot-box span.active {
opacity: 1;
}
```
3. JavaScript代码
```javascript
var container = document.querySelector('.container');
var imgBox = document.querySelector('.img-box');
var dots = document.querySelectorAll('.dot-box span');
var index = 0;
var timer = null;
var startX = 0;
var startY = 0;
var moveX = 0;
var moveY = 0;
var distanceX = 0;
var distanceY = 0;
// 自动轮播
timer = setInterval(function() {
index++;
if (index > 3) {
index = 0;
}
changeImage();
}, 2000);
// 触摸事件
container.addEventListener('touchstart', function(e) {
clearInterval(timer);
startX = e.touches.clientX;
startY = e.touches.clientY;
});
container.addEventListener('touchmove', function(e) {
moveX = e.touches.clientX;
moveY = e.touches.clientY;
distanceX = moveX - startX;
distanceY = moveY - startY;
imgBox.style.transform = 'translateX(' + (-index * 100 - distanceX) / 4 + '%)';
});
container.addEventListener('touchend', function(e) {
if (Math.abs(distanceX) > 50) {
if (distanceX > 0) {
index--;
if (index < 0) {
index = 3;
}
} else {
index++;
if (index > 3) {
index = 0;
}
}
}
changeImage();
timer = setInterval(function() {
index++;
if (index > 3) {
index = 0;
}
changeImage();
}, 2000);
});
// 点击事件
dots.forEach(function(dot, i) {
dot.addEventListener('click', function() {
index = i;
changeImage();
});
});
// 切换图片和小圆点的样式
function changeImage() {
imgBox.style.transform = 'translateX(' + (-index * 100) + '%)';
dots.forEach(function(dot) {
dot.classList.remove('active');
});
dots[index].classList.add('active');
}
```