jquery实现轮播图移入圆点可切换代码
时间: 2024-03-19 09:45:00 浏览: 54
好的,以下是一个简单的示例代码:
HTML部分:
```html
<div class="slider">
<ul class="slides">
<li><img src="image1.jpg"></li>
<li><img src="image2.jpg"></li>
<li><img src="image3.jpg"></li>
</ul>
<ul class="dots">
<li class="dot active"></li>
<li class="dot"></li>
<li class="dot"></li>
</ul>
</div>
```
CSS部分:
```css
.slider {
position: relative;
width: 500px;
height: 400px;
}
.slides {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
list-style: none;
margin: 0;
padding: 0;
}
.slides li {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
opacity: 0;
transition: opacity 0.5s ease-in-out;
}
.slides li.active {
opacity: 1;
}
.dots {
position: absolute;
left: 50%;
bottom: 20px;
transform: translateX(-50%);
list-style: none;
margin: 0;
padding: 0;
}
.dots li {
display: inline-block;
width: 10px;
height: 10px;
border-radius: 50%;
background-color: #ccc;
margin: 0 5px;
cursor: pointer;
}
.dots li.active {
background-color: #333;
}
```
JavaScript部分:
```javascript
var currentSlide = 0;
var slides = $('.slides li');
var dots = $('.dots li');
// 初始化
slides.eq(currentSlide).addClass('active');
dots.eq(currentSlide).addClass('active');
// 点击圆点切换
dots.click(function() {
currentSlide = $(this).index();
slides.removeClass('active').eq(currentSlide).addClass('active');
dots.removeClass('active').eq(currentSlide).addClass('active');
});
// 自动轮播
setInterval(function() {
currentSlide++;
if (currentSlide >= slides.length) {
currentSlide = 0;
}
slides.removeClass('active').eq(currentSlide).addClass('active');
dots.removeClass('active').eq(currentSlide).addClass('active');
}, 3000);
// 鼠标移入停止自动轮播
$('.slider').hover(function() {
clearInterval(autoSlide);
}, function() {
autoSlide = setInterval(function() {
currentSlide++;
if (currentSlide >= slides.length) {
currentSlide = 0;
}
slides.removeClass('active').eq(currentSlide).addClass('active');
dots.removeClass('active').eq(currentSlide).addClass('active');
}, 3000);
});
```
以上代码实现了一个简单的轮播图,当鼠标移入圆点时可以切换到对应的图片。希望可以帮到你!
阅读全文