javascript故宫轮播
时间: 2024-01-08 13:21:20 浏览: 98
JavaScript 图片轮播特效代码
根据提供的引用内容,以下是一个使用JavaScript实现故宫轮播的例子:
```javascript
// HTML部分
<div id="carousel">
<img src="image1.jpg" alt="Image 1">
<img src="image2.jpg" alt="Image 2">
<img src="image3.jpg" alt="Image 3">
</div>
// CSS部分
#carousel {
width: 500px;
height: 300px;
overflow: hidden;
}
#carousel img {
width: 100%;
height: 100%;
object-fit: cover;
}
// JavaScript部分
const carousel = document.getElementById('carousel');
const images = carousel.getElementsByTagName('img');
let currentIndex = 0;
function showImage(index) {
for (let i = 0; i < images.length; i++) {
images[i].style.display = 'none';
}
images[index].style.display = 'block';
}
function nextImage() {
currentIndex++;
if (currentIndex >= images.length) {
currentIndex = 0;
}
showImage(currentIndex);
}
function previousImage() {
currentIndex--;
if (currentIndex < 0) {
currentIndex = images.length - 1;
}
showImage(currentIndex);
}
// 初始化显示第一张图片
showImage(currentIndex);
// 点击下一张按钮切换到下一张图片
document.getElementById('nextButton').addEventListener('click', nextImage);
// 点击上一张按钮切换到上一张图片
document.getElementById('previousButton').addEventListener('click', previousImage);
```
阅读全文