html手动自动轮播源代码,切换用箭头
时间: 2024-02-24 10:53:12 浏览: 31
以下是一个简单的 HTML 手动轮播的源代码,可以让用户通过点击箭头来切换图片:
```html
<!DOCTYPE html>
<html>
<head>
<title>手动轮播</title>
<style type="text/css">
.carousel {
position: relative;
width: 500px;
height: 300px;
margin: 0 auto;
overflow: hidden;
}
.carousel img {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
opacity: 0;
transition: opacity 1s ease-in-out;
}
.carousel img.active {
opacity: 1;
}
.carousel button {
position: absolute;
top: 50%;
transform: translateY(-50%);
padding: 10px;
background-color: #ccc;
border: none;
cursor: pointer;
font-size: 18px;
}
.carousel button.prev {
left: 0;
}
.carousel button.next {
right: 0;
}
.carousel button svg {
width: 20px;
height: 20px;
}
</style>
</head>
<body>
<div class="carousel">
<img src="image1.jpg" class="active">
<img src="image2.jpg">
<img src="image3.jpg">
<button class="prev"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12l4.58-4.59z"/></svg></button>
<button class="next"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M8.59 16.59L10 18l6-6-6-6-1.41 1.41L13.17 12l-4.58 4.59z"/></svg></button>
</div>
<script type="text/javascript">
var carousel = document.querySelector('.carousel');
var prevBtn = carousel.querySelector('.prev');
var nextBtn = carousel.querySelector('.next');
var images = carousel.querySelectorAll('img');
var currentIndex = 0;
function showImage(index) {
images[currentIndex].classList.remove('active');
images[index].classList.add('active');
currentIndex = index;
}
prevBtn.addEventListener('click', function() {
var index = currentIndex - 1;
if (index < 0) {
index = images.length - 1;
}
showImage(index);
});
nextBtn.addEventListener('click', function() {
var index = currentIndex + 1;
if (index >= images.length) {
index = 0;
}
showImage(index);
});
</script>
</body>
</html>
```
在这个例子中,我们使用了 Font Awesome 提供的 SVG 图标来作为轮播箭头。在 CSS 中,我们将箭头的宽度和高度设置为 20px,并使用 `transform` 来将箭头垂直居中。在 JavaScript 中,我们按照与上一个例子相同的方式计算要显示的图片的索引,然后通过 `classList` 来添加或删除 `active` 类,从而切换图片的显示。