实现焦点轮播图的效果,有01.jpg,02.jpg,03.jpg三张图片,要求如下:1.当页面加载完成后,每2秒自动切换一张图片,2.切换图片时,其对应按钮的样式同步变换——背景颜色变成红色,3.当鼠标悬停在某个按钮上时,显示该按钮对应的图片且轮播停止,给出完整代码
时间: 2023-12-04 07:04:16 浏览: 62
jQuery实现的左右箭头控制图片轮播焦点图幻灯效果源码.zip
HTML代码:
```
<div class="banner">
<ul class="img-list">
<li><img src="01.jpg"></li>
<li><img src="02.jpg"></li>
<li><img src="03.jpg"></li>
</ul>
<ul class="btn-list">
<li class="active"></li>
<li></li>
<li></li>
</ul>
</div>
```
CSS代码:
```
.banner {
position: relative;
width: 600px;
height: 300px;
overflow: hidden;
}
.img-list {
position: absolute;
left: 0;
top: 0;
width: 1800px;
height: 300px;
margin: 0;
padding: 0;
}
.img-list li {
float: left;
list-style: none;
width: 600px;
height: 300px;
}
.btn-list {
position: absolute;
right: 20px;
bottom: 20px;
z-index: 999;
margin: 0;
padding: 0;
}
.btn-list li {
float: left;
width: 20px;
height: 20px;
margin-left: 10px;
border-radius: 50%;
background-color: #ddd;
cursor: pointer;
}
.btn-list li.active {
background-color: red;
}
```
JavaScript代码:
```
var banner = document.querySelector('.banner');
var imgList = banner.querySelector('.img-list');
var btnList = banner.querySelector('.btn-list');
var btns = btnList.querySelectorAll('li');
var len = btns.length;
var index = 0;
var timer = null;
// 自动轮播
function autoplay() {
timer = setInterval(function() {
index++;
if (index >= len) {
index = 0;
}
changeImg(index);
}, 2000);
}
// 切换图片
function changeImg(curIndex) {
imgList.style.left = -curIndex * 600 + 'px';
for (var i = 0; i < len; i++) {
btns[i].classList.remove('active');
}
btns[curIndex].classList.add('active');
}
// 鼠标悬停
banner.addEventListener('mouseover', function() {
clearInterval(timer);
});
// 鼠标移开
banner.addEventListener('mouseout', function() {
autoplay();
});
// 点击按钮
for (var i = 0; i < len; i++) {
btns[i].index = i;
btns[i].addEventListener('click', function() {
index = this.index;
changeImg(index);
});
}
autoplay();
```
阅读全文