HTML、CSS、JS实现轮播图效果:包含分页按钮及切换箭头
以下是一个使用HTML、CSS和JavaScript实现的简单轮播图效果的示例代码。该示例包括分页按钮和切换箭头。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image Slider</title>
<style>
.slider {
position: relative;
width: 300px;
height: 200px;
margin: auto;
}
.slider img {
width: 100%;
height: 100%;
position: absolute;
opacity: 0;
transition: opacity 0.5s;
}
.slider img.active {
opacity: 1;
}
.pagination {
position: absolute;
bottom: 10px;
left: 50%;
transform: translateX(-50%);
}
.pagination button {
cursor: pointer;
padding: 5px;
margin: 0 5px;
background-color: #ddd;
border: none;
outline: none;
}
.pagination button.active {
background-color: #007bff;
color: white;
}
.arrow {
cursor: pointer;
position: absolute;
top: 50%;
transform: translateY(-50%);
font-size: 30px;
color: #ddd;
user-select: none;
}
.arrow:hover {
color: #007bff;
}
</style>
</head>
<body>
<div class="slider">
<img src="image1.jpg" class="active">
<img src="image2.jpg">
<img src="image3.jpg">
<div class="arrow left">❮</div>
<div class="arrow right">❯</div>
<div class="pagination">
<button class="active"></button>
<button></button>
<button></button>
</div>
</div>
<script>
let index = 0;
const images = document.querySelectorAll('.slider img');
const pagination = document.querySelectorAll('.pagination button');
const leftArrow = document.querySelector('.left');
const rightArrow = document.querySelector('.right');
function showImage(imageIndex) {
images.forEach((img, i) => img.classList.toggle('active', i === imageIndex));
pagination.forEach((button, i) => button.classList.toggle('active', i === imageIndex));
}
showImage(index);
rightArrow.addEventListener('click', () => {
index = (index + 1) % images.length;
showImage(index);
});
leftArrow.addEventListener('click', () => {
index = (index + images.length - 1) % images.length;
showImage(index);
});
pagination.forEach((button, i) => {
button.addEven
评论已关闭