jQuery轮播图代码
时间: 2024-02-11 18:02:05 浏览: 87
jquery轮播图代码
5星 · 资源好评率100%
以下是一个简单的jQuery轮播图代码示例:
```html
<!DOCTYPE html>
<html>
<head>
<title>jQuery轮播图</title>
<style>
.slider {
width: 500px;
height: 300px;
overflow: hidden;
position: relative;
}
.slider img {
width: 100%;
height: 100%;
}
.slider .prev, .slider .next {
position: absolute;
top: 50%;
transform: translateY(-50%);
background-color: rgba(0, 0, 0, 0.5);
color: #fff;
padding: 10px;
cursor: pointer;
}
.slider .prev {
left: 10px;
}
.slider .next {
right: 10px;
}
</style>
</head>
<body>
<div class="slider">
<img src="image1.jpg" alt="Image 1">
<img src="image2.jpg" alt="Image 2">
<img src="image3.jpg" alt="Image 3">
<img src="image4.jpg" alt="Image 4">
</div>
<script src="js/jquery-1.12.3.min.js"></script>
<script>
$(document).ready(function() {
var currentIndex = 0;
var images = $('.slider img');
var totalImages = images.length;
function showImage(index) {
images.hide();
images.eq(index).show();
}
function nextImage() {
currentIndex++;
if (currentIndex >= totalImages) {
currentIndex = 0;
}
showImage(currentIndex);
}
function prevImage() {
currentIndex--;
if (currentIndex < 0) {
currentIndex = totalImages - 1;
}
showImage(currentIndex);
}
$('.slider .next').click(function() {
nextImage();
});
$('.slider .prev').click(function() {
prevImage();
});
showImage(currentIndex);
});
</script>
</body>
</html>
```
这段代码创建了一个简单的轮播图,包含了四张图片。通过点击“上一张”和“下一张”按钮可以切换图片。你可以根据需要修改图片路径和样式。
阅读全文