初学者用web前端写一个手动图片滚动的简易程序
时间: 2023-09-20 15:12:20 浏览: 45
好的,以下是一个简单的手动图片滚动程序的示例代码:
HTML部分:
```
<div id="image-slider">
<img src="img1.jpg" alt="Image 1">
<img src="img2.jpg" alt="Image 2">
<img src="img3.jpg" alt="Image 3">
<button id="prev-btn">‹</button>
<button id="next-btn">›</button>
</div>
```
CSS部分:
```
#image-slider {
width: 600px;
height: 300px;
overflow: hidden;
position: relative;
}
#image-slider img {
width: 600px;
height: 300px;
position: absolute;
top: 0;
left: 0;
opacity: 0;
transition: opacity 0.5s ease-in-out;
}
#image-slider img.show {
opacity: 1;
}
#prev-btn, #next-btn {
position: absolute;
top: 50%;
transform: translateY(-50%);
border: none;
background-color: transparent;
color: white;
font-size: 20px;
cursor: pointer;
}
#prev-btn {
left: 20px;
}
#next-btn {
right: 20px;
}
```
JavaScript部分:
```
var slider = document.querySelector("#image-slider");
var images = slider.querySelectorAll("img");
var currentIndex = 0;
var prevBtn = document.querySelector("#prev-btn");
var nextBtn = document.querySelector("#next-btn");
function showImage(index) {
images[currentIndex].classList.remove("show");
images[index].classList.add("show");
currentIndex = index;
}
prevBtn.addEventListener("click", function() {
var index = currentIndex - 1;
if (index < 0) {
index = images.length - 1;
}
showImage(index);
});
nextBtn.addEventListener("click", function() {
var index = (currentIndex + 1) % images.length;
showImage(index);
});
showImage(currentIndex);
```
这个示例程序会在页面加载时显示第一张图片,同时显示两个按钮,当点击按钮时会手动切换至上一张或下一张图片。您可以根据自己的需求修改图片的数量、大小和滚动速度等参数。