【HTML】解析垂直滚动轮播效果的HTML、CSS和JavaScript实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vertical Carousel Example</title>
<style>
.carousel {
width: 300px;
height: 400px;
overflow: hidden;
position: relative;
}
.carousel-content {
width: 100%;
height: auto;
display: flex;
flex-direction: column;
align-items: center;
justify-content: space-between;
padding: 10px;
box-sizing: border-box;
}
.carousel-item {
width: 100%;
height: 100px;
margin: 5px;
background-color: #f3f3f3;
display: flex;
align-items: center;
justify-content: center;
font-size: 20px;
}
</style>
</head>
<body>
<div class="carousel">
<div class="carousel-content">
<div class="carousel-item">1</div>
<div class="carousel-item">2</div>
<div class="carousel-item">3</div>
<div class="carousel-item">4</div>
<div class="carousel-item">5</div>
</div>
</div>
<script>
// JavaScript code to handle the vertical carousel scrolling
const carousel = document.querySelector('.carousel');
const carouselContent = document.querySelector('.carousel-content');
let start = 0;
function onTouchStart(e) {
start = e.touches[0].clientY;
}
function onTouchMove(e) {
const current = e.touches[0].clientY;
const delta = current - start;
const transform = carouselContent.style.transform;
const translate = transform ? Number(transform.match(/-?\d+/)[0]) : 0;
carouselContent.style.transform = `translateY(${translate + delta}px)`;
start = current;
}
carousel.addEventListener('touchstart', onTouchStart);
carousel.addEventListener('touchmove', onTouchMove);
</script>
</body>
</html>
这段代码实现了一个简单的垂直滚动轮播效果,用户可以通过触摸屏进行上下滑动。HTML定义了轮播的结构,CSS负责样式布局,JavaScript处理触摸事件以及滚动逻辑。这个例子教会开发者如何使用HTML、CSS和JavaScript创建移动端友好的交互效果。
评论已关闭