写一个简单的背景图片轮播
时间: 2024-11-05 20:27:06 浏览: 19
创建一个简单的背景图片轮播通常需要HTML、CSS和JavaScript(或者jQuery这样的库)。以下是一个基本的示例,使用纯CSS来实现静态图片轮播:
```html
<!DOCTYPE html>
<html lang="zh">
<head>
<style>
.slideshow {
position: relative;
width: 100%;
height: 400px;
overflow: hidden;
}
.slideshow img {
position: absolute;
top: 0;
left: 0;
opacity: 0;
transition: opacity 1s ease-in-out;
}
.slideshow img.active {
opacity: 1;
}
.slideshow:hover img {
opacity: 0.5;
}
/* 添加图片切换按钮样式 */
.controls button {
display: block;
position: absolute;
bottom: 20px;
width: 50px;
height: 50px;
cursor: pointer;
}
</style>
</head>
<body>
<div class="slideshow">
<img src="image1.jpg" alt="Image 1" class="active">
<img src="image2.jpg" alt="Image 2">
<img src="image3.jpg" alt="Image 3">
</div>
<!-- 切换按钮 -->
<div class="controls">
<button onclick="prevSlide()">上一张</button>
<button onclick="nextSlide()">下一张</button>
</div>
<script>
let current = 0;
function prevSlide() {
if (current > 0) {
current--;
document.querySelector('.slideshow img').classList.remove('active');
document.querySelector(`.slideshow img:nth-child(${current+1})`).classList.add('active');
}
}
function nextSlide() {
if (current < 2) {
current++;
document.querySelector('.slideshow img').classList.remove('active');
document.querySelector(`.slideshow img:nth-child(${current+1})`).classList.add('active');
}
}
</script>
</body>
</html>
```
这个例子中,图片轮播默认显示第一张图片,并提供两个按钮用于切换到上一张或下一张。通过JavaScript控制图片的`opacity`属性来实现淡入淡出效果。
阅读全文