JS特效第105弹:html5手机触摸滑动图片幻灯片轮播切换代码
以下是一个简化版的HTML和JavaScript代码示例,用于创建一个简单的HTML5手机触摸滑动图片幻灯片轮播效果。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>滑动图片轮播</title>
<style>
.slider {
overflow: hidden;
position: relative;
}
.slider img {
width: 100%;
display: block;
}
</style>
</head>
<body>
<div id="slider" class="slider">
<img src="slide1.jpg" alt="Slide 1">
<img src="slide2.jpg" alt="Slide 2">
<img src="slide3.jpg" alt="Slide 3">
</div>
<script>
let sliderImages = document.querySelectorAll('#slider img');
let currentIndex = 0;
let touchStart = 0;
document.getElementById('slider').addEventListener('touchstart', function(e) {
touchStart = e.changedTouches[0].clientX;
});
document.getElementById('slider').addEventListener('touchmove', function(e) {
e.preventDefault();
});
document.getElementById('slider').addEventListener('touchend', function(e) {
let touchEnd = e.changedTouches[0].clientX;
if (touchEnd - touchStart > 100) { // 右滑
changeSlide(-1);
} else if (touchStart - touchEnd > 100) { // 左滑
changeSlide(1);
}
});
function changeSlide(direction) {
let nextIndex = currentIndex + direction;
if (nextIndex < 0) {
nextIndex = sliderImages.length - 1;
} else if (nextIndex >= sliderImages.length) {
nextIndex = 0;
}
sli
评论已关闭