用jquery写轮播图 手动点击切换图片
时间: 2023-07-18 08:18:22 浏览: 63
好的,以下是一个简单的用 jQuery 实现手动点击切换图片的轮播图代码:
HTML 代码:
```html
<div class="slider">
<div class="slider-wrapper">
<img src="img/img1.jpg">
<img src="img/img2.jpg">
<img src="img/img3.jpg">
</div>
<div class="slider-nav">
<span class="slider-nav-item"></span>
<span class="slider-nav-item"></span>
<span class="slider-nav-item"></span>
</div>
</div>
```
CSS 代码:
```css
.slider {
position: relative;
width: 100%;
height: 400px;
overflow: hidden;
}
.slider-wrapper {
position: absolute;
width: 300%;
height: 100%;
left: -100%;
}
.slider-wrapper img {
float: left;
width: 33.3333%;
height: 100%;
}
.slider-nav {
position: absolute;
left: 50%;
bottom: 20px;
transform: translateX(-50%);
}
.slider-nav-item {
display: inline-block;
width: 10px;
height: 10px;
margin-right: 10px;
border-radius: 50%;
background-color: #ccc;
cursor: pointer;
}
.slider-nav-item.active {
background-color: #f00;
}
```
JavaScript 代码:
```javascript
$(function() {
var $slider = $('.slider');
var $wrapper = $('.slider-wrapper');
var $nav = $('.slider-nav');
var $navItem = $('.slider-nav-item');
var currentIndex = 0;
var timer;
// 初始化
$navItem.eq(currentIndex).addClass('active');
$wrapper.css('left', -currentIndex * 100 + '%');
// 点击导航切换图片
$navItem.on('click', function() {
var index = $(this).index();
if (index === currentIndex) {
return;
}
$navItem.eq(currentIndex).removeClass('active');
$navItem.eq(index).addClass('active');
$wrapper.animate({left: -index * 100 + '%'}, 500);
currentIndex = index;
});
// 自动轮播
function autoPlay() {
timer = setInterval(function() {
currentIndex = (currentIndex + 1) % $navItem.length;
$navItem.eq(currentIndex).trigger('click');
}, 2000);
}
autoPlay();
// 鼠标悬停暂停轮播
$slider.on('mouseenter', function() {
clearInterval(timer);
}).on('mouseleave', function() {
autoPlay();
});
});
```
这段代码实现了一个具有导航按钮的轮播图,点击导航按钮可以切换图片,同时具有自动轮播和鼠标悬停暂停轮播的功能。