HTML5用一张图片制作轮播图,并添加手动切换功能
时间: 2024-10-10 15:14:09 浏览: 38
jQuery图片轮播切换
使用HTML5制作带有手动切换功能的轮播图,可以通过结合HTML、CSS和JavaScript来实现。以下是一个简单的示例:
1. **HTML部分**:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>轮播图</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="slider">
<img src="image1.jpg" alt="Image 1" class="slide" id="currentSlide">
<img src="image2.jpg" alt="Image 2" class="slide">
<img src="image3.jpg" alt="Image 3" class="slide">
</div>
<button onclick="changeSlide(-1)">上一张</button>
<button onclick="changeSlide(1)">下一张</button>
<script src="script.js"></script>
</body>
</html>
```
2. **CSS部分** (`styles.css`):
```css
.slider {
width: 500px;
height: 300px;
overflow: hidden;
position: relative;
}
.slide {
width: 100%;
height: 100%;
position: absolute;
transition: opacity 0.5s ease-in-out;
opacity: 0;
}
#currentSlide {
opacity: 1;
}
```
3. **JavaScript部分** (`script.js`):
```javascript
let currentIndex = 0;
const slides = document.querySelectorAll('.slide');
function showSlide(index) {
if (index >= slides.length) index = 0;
if (index < 0) index = slides.length - 1;
for (let i = 0; i < slides.length; i++) {
slides[i].style.opacity = i === index ? '1' : '0';
}
currentIndex = index;
}
function changeSlide(direction) {
showSlide(currentIndex + direction);
}
document.getElementById('currentSlide').addEventListener('click', () => changeSlide(1));
```
在这个示例中,我们首先在HTML中创建了一个包含三张图片的轮播图容器,并添加了两个按钮用于手动切换图片。通过CSS,我们隐藏了除当前显示图片外的其他图片。最后,通过JavaScript实现了点击按钮时切换到上一张或下一张图片的功能。
阅读全文