html网页制作滚动图片
时间: 2024-06-09 14:02:14 浏览: 84
html实现图片滚动
以下是一个使用HTML、CSS和JavaScript制作网页滚动图片的示例:
HTML代码:
```html
<div class="slider">
<ul class="slides">
<li><img src="image1.jpg" alt="Image 1"></li>
<li><img src="image2.jpg" alt="Image 2"></li>
<li><img src="image3.jpg" alt="Image 3"></li>
</ul>
<button class="prev">Previous</button>
<button class="next">Next</button>
</div>
```
CSS代码:
```css
.slider {
position: relative;
width: 500px;
height: 300px;
overflow: hidden;
}
.slides {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
list-style: none;
margin: 0;
padding: 0;
}
.slides li {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
opacity: 0;
transition: opacity 0.5s ease-in-out;
}
.slides li.active {
opacity: 1;
}
.prev,
.next {
position: absolute;
top: 50%;
transform: translateY(-50%);
padding: 10px;
background-color: #ccc;
border: none;
color: #fff;
cursor: pointer;
}
.prev {
left: 10px;
}
.next {
right: 10px;
}
```
JavaScript代码:
```javascript
const slides = document.querySelectorAll('.slides li');
const prevBtn = document.querySelector('.prev');
const nextBtn = document.querySelector('.next');
let currentSlide = 0;
function showSlide(slideIndex) {
slides.forEach((slide) => {
slide.classList.remove('active');
});
slides[slideIndex].classList.add('active');
}
function prevSlide() {
currentSlide--;
if (currentSlide < 0) {
currentSlide = slides.length - 1;
}
showSlide(currentSlide);
}
function nextSlide() {
currentSlide++;
if (currentSlide >= slides.length) {
currentSlide = 0;
}
showSlide(currentSlide);
}
prevBtn.addEventListener('click', prevSlide);
nextBtn.addEventListener('click', nextSlide);
showSlide(currentSlide);
```
这个示例中,我们使用了一个包含图片的`<ul>`元素来创建滚动图片的容器。通过JavaScript代码,我们为"Previous"和"Next"按钮添加了点击事件,点击按钮时会切换到上一张或下一张图片。CSS代码用于设置容器和图片的样式。
阅读全文