// JavaScript 代码
```
1.2 CSS样式
使用CSS样式来定义div容器的样式,以及按钮容器中按钮的样式。
```css
/ 样式代码 /
carousel {
width: 500px;
height: 300px;
position: relative;
overflow: hidden;
}
.image-container {
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
}
.image-container img {
width: 100%;
height: 100%;
object-fit: cover;
}
.button-container {
position: absolute;
bottom: 0;
left: 0;
width: 100%;
height: 50px;
display: flex;
justify-content: center;
align-items: center;
}
.button-container button {
width: 50px;
height: 50px;
border-radius: 50%;
background-color: fff;
color: 000;
cursor: pointer;
}
.button-container button:hover {
background-color: ccc;
}
```
1.3 JavaScript脚本
使用JavaScript脚本来实现图片轮播的功能,包括图片切换、按钮控制、自动轮播等。
```javascript
// JavaScript 代码
const carousel = document.getElementById(carousel);
const imageContainer = document.querySelector(.image-container);
const prevButton = document.querySelector(.prev);
const nextButton = document.querySelector(.next);
let currentImageIndex = 0;
const images = document.querySelectorAll(.image-container img);
images.forEach((image, index) => {
if (index == currentImageIndex) {
image.style.display = none;
}
});
prevButton.addEventListener(click, () => {
currentImageIndex--;
if (currentImageIndex < 0) {
currentImageIndex = images.length - 1;
}
showImage();
});
nextButton.addEventListener(click, () => {
currentImageIndex++;
if (currentImageIndex > images.length - 1) {
currentImageIndex = 0;
}
showImage();
});
function showImage() {
images.forEach((image, index) => {
if (index === currentImageIndex) {
image.style.display = block;
} else {
image.style.display = none;
}
});
}
let autoSlideInterval = setInterval(nextImage, 3000);
function nextImage() {
currentImageIndex++;
if (currentImageIndex > images.length - 1) {
currentImageIndex = 0;
}
showImage();
}
carousel.addEventListener(mouseover, () => {
clearInterval(autoSlideInterval);
});
carousel.addEventListener(mouseout, () => {
autoSlideInterval = setInterval(nextImage, 3000);
});
```
二、使用JavaScript库实现图片轮播
2.1 jQuery轮播
jQuery是一个JavaScript库,它提供了许多方便的函数和方法,可以帮助我们快速实现图片轮播的功能。
```html
图片轮播
/ 样式代码 /
发表评论