html css js实现无缝轮播图思路及其实现
<!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 {
position: relative;
width: 300px;
height: 200px;
margin: auto;
overflow: hidden;
}
.slider img {
width: 300px;
height: 200px;
position: absolute;
transition: transform 0.5s ease-in-out;
}
</style>
</head>
<body>
<div class="slider">
<img src="image1.jpg" alt="Image 1" class="active">
<img src="image2.jpg" alt="Image 2">
<img src="image3.jpg" alt="Image 3">
</div>
<script>
let currentIndex = 0;
const images = document.querySelectorAll('.slider img');
const imageCount = images.length;
function showImage(index) {
images[currentIndex].style.transform = 'translateX(100%)';
images[index].style.transform = 'translateX(0)';
currentIndex = index;
}
function nextImage() {
const nextIndex = (currentIndex + 1) % imageCount;
showImage(nextIndex);
}
function startSlider() {
setInterval(nextImage, 3000);
}
startSlider();
</script>
</body>
</html>
这个简单的无缝轮播图示例使用了基本的HTML、CSS和JavaScript。轮播图中有三张图片,每张图片都是绝对定位的,并且初始都在左侧(translateX(100%)
)。当轮播开始时,当前活动图片会移动到右侧(translateX(0)
),而下一张图片会移动到视图中(translateX(100%)
变为translateX(0)
)。这个例子使用了简单的模运算来处理图片的索引循环。
评论已关闭