jquery实现左右箭头对图片轮播的切换
时间: 2023-07-20 10:11:23 浏览: 170
可以使用jQuery实现左右箭头对图片轮播的切换,代码如下:
HTML部分:
```
<div class="slider">
<ul class="slider-list">
<li><img src="img1.jpg"></li>
<li><img src="img2.jpg"></li>
<li><img src="img3.jpg"></li>
</ul>
<a class="slider-arrow slider-prev" href="javascript:void(0);"><</a>
<a class="slider-arrow slider-next" href="javascript:void(0);">></a>
</div>
```
CSS部分:
```
.slider {
position: relative;
width: 500px;
height: 300px;
overflow: hidden;
}
.slider-list {
position: absolute;
left: 0;
top: 0;
width: 1500px;
height: 300px;
margin: 0;
padding: 0;
}
.slider-list li {
float: left;
list-style: none;
width: 500px;
height: 300px;
}
.slider-arrow {
position: absolute;
top: 50%;
margin-top: -20px;
width: 40px;
height: 40px;
line-height: 40px;
text-align: center;
font-size: 24px;
color: #fff;
background-color: rgba(0, 0, 0, 0.5);
text-decoration: none;
border-radius: 50%;
}
.slider-prev {
left: 20px;
}
.slider-next {
right: 20px;
}
```
jQuery部分:
```
$(function() {
var sliderList = $('.slider-list');
var sliderItem = $('.slider-list li');
var sliderCount = sliderItem.length;
var sliderWidth = sliderItem.width();
var sliderHeight = sliderItem.height();
var sliderArrow = $('.slider-arrow');
var currentIndex = 0;
sliderList.width(sliderWidth * sliderCount);
sliderArrow.on('click', function() {
var direction = $(this).hasClass('slider-prev') ? -1 : 1;
currentIndex += direction;
if (currentIndex === -1) {
currentIndex = sliderCount - 1;
} else if (currentIndex === sliderCount) {
currentIndex = 0;
}
sliderList.animate({left: -sliderWidth * currentIndex}, 500);
});
});
```
以上代码实现了一个简单的左右箭头图片轮播,点击左箭头向左切换图片,点击右箭头向右切换图片。注意要将图片的宽度和高度设置好,使得图片排列在一行。
阅读全文