html+css制作轮播图代码
时间: 2024-10-18 22:20:14 浏览: 31
JS+DIV无缝滚动代码
4星 · 用户满意度95%
使用HTML和CSS制作简单的轮播图,通常会结合`<div>`元素、CSS伪类`:hover`和`transition`属性。下面是一个基础的示例:
HTML部分:
```html
<div class="carousel">
<img src="image1.jpg" alt="Image 1">
<img src="image2.jpg" alt="Image 2">
<img src="image3.jpg" alt="Image 3">
<a class="prev" href="#"><</a>
<a class="next" href="#">></a>
</div>
```
CSS部分 (假设宽度为700px,轮播图容器宽度自动分配给所有图片):
```css
.carousel {
position: relative;
width: 100%;
}
.carousel img {
display: none; /* 隐藏初始图片 */
transition: opacity 0.5s ease-in-out;
}
.carousel img.active {
display: block;
}
.carousel .prev,
.carousel .next {
position: absolute;
top: 50%;
transform: translateY(-50%);
z-index: 1;
cursor: pointer;
}
.carousel .prev {
left: 20px;
}
.carousel .next {
right: 20px;
}
.carousel:hover .prev {
opacity: 0.5;
}
.carousel:hover .next {
opacity: 0.5;
}
```
JavaScript (可选) 可以用于添加更复杂的交互,比如点击按钮切换图片:
```javascript
var images = document.querySelectorAll('.carousel img');
var currentSlide = 0;
function changeSlide(direction) {
images[currentSlide].classList.remove('active');
if (direction === 'prev') {
currentSlide--;
if (currentSlide < 0) currentSlide = images.length - 1;
} else {
currentSlide++;
if (currentSlide >= images.length) currentSlide = 0;
}
images[currentSlide].classList.add('active');
}
document.querySelector('.prev').addEventListener('click', function() { changeSlide('prev'); });
document.querySelector('.next').addEventListener('click', function() { changeSlide('next'); });
```
阅读全文