利用面向对象的思维,实现一个简易的轮播图功能。
html部分:
<div id="box">
<div id="pic">
<img src="images/1.jpg" style="display: block;">
<img src="images/2.jpg" >
<img src="images/3.jpg" >
<img src="images/4.jpg" >
</div>
<div id="pag">
<div class="page" id="active">1</div>
<div class="page">2</div>
<div class="page">3</div>
<div class="page">4</div>
</div>
</div>
css部分:
* {
margin: 0;
padding: 0;
}
#box {
width: 740px;
height: 460px;
position: relative;
}
#pag {
position: absolute;
bottom: 30px;
right: 50px;
display: flex;
}
.page {
width: 30px;
height: 30px;
line-height: 30px;
margin-left: 10px;
background-color: pink;
color: #fff;
text-align: center;
}
#pic img {
display: none;
}
#active {
background-color: #000000;
}
JS部分:
// 创建实例
window.onload = function() {
var lunbo = new Piclunbo();
lunbo.autoplay();
lunbo.hoverIcon();
}
// 构造函数
function Piclunbo() {
this.opic = document.getElementsByTagName('img');
this.opage = document.getElementsByClassName('page');
this.len = this.opage.length;
this.num = 0;
}
// 自动轮播
Piclunbo.prototype.autoplay = function() {
var This = this;
setInterval(function() {
if (This.num == This.len - 1) {
This.num = 0
} else {
This.num++
}
for (var i = 0; i < This.len; i++) {
This.opage[i].id = '';
This.opic[i].style.display = 'none';
}
This.opage[This.num].id = 'active';
This.opic[This.num].style.display = 'block';
}, 2000)
}
// 鼠标滑过效果
Piclunbo.prototype.hoverIcon = function() {
var This = this;
for (let i = 0; i < This.len; i++) {
This.opage[i].onmouseover = function() {
for (var j = 0; j < This.len; j++) {
This.opage[j].id = '';
This.opic[j].style.display = 'none';
}
This.num = i;
This.opage[This.num].id = 'active';
This.opic[This.num].style.display = 'block'
}
}
}
最终效果:
1.使用定时器,实现图片的自动轮播。
2.鼠标滑过页码,实现图片的指定跳转。