jQuery图片轮播实现并封装(一)

2020-05-24 21:47:26易采站长站整理

利用面向对象自己动手写了一个封装好的jquery轮播对象,可满足一般需求,需要使用时只需调用此对象的轮播方法即可。

demo:https://github.com/zsqosos/shopweb

具体代码如下:

HTML结构:


<div class="banner" id="J_bg_ban">
  <ul>
    <li><a href="#"><img src="banner_04.jpg" alt="广告图 /></a></li>
    <li><a href="#"><img src="banner_04.jpg" alt="广告图 /></a></li>
    <li><a href="#"><img src="banner_03.jpg" alt="广告图"/></a></li>
    <li><a href="#"><img src="banner_04.jpg" alt="广告图"/></a></li>
    <li><a href="#"><img src="banner_05.jpg" alt="广告图"/></a></li>
  </ul>
  <div class="indicator" id="J_bg_indicator">
  </div>
  <div class="ban-btn clearfloat" id="J_bg_btn">
    <a class="next-btn fr" href="javascript:">></a><a class="prev-btn fl" href="javascript:"><</a>
  </div>
</div>

 css样式:


.banner {
height: 325px;
width: 812px;
position: relative;
overflow: hidden;
}
.banner ul li{
position: absolute;
  top: 0;
  left: 0;
}
.banner ul li img{
height: 325px;
width: 812px;
display: block;
}
.ban-btn{
width: 100%;
position: absolute;
top: 136px;
z-index: 2;
}
.ban-btn a{
display: inline-block;
height: 60px;
width: 35px;
background: rgba(180,180,180,0.5);
font-size: 25px;
text-align: center;
line-height: 60px;
color: #fff;
}
.ban-btn a:hover{
background: rgba(100,100,100,0.5);
}
.indicator{
width: 100%;
position: absolute;
text-align: center;
bottom: 15px;
z-index: 2;
}
.indicator a{
display: inline-block;
width: 20px;
height: 5px;
margin:0 3px;
background: #fff;
}
.indicator-active{
background: #FF8C00!important;
}

jquery代码:


$.carousel = {
now : 0, //当前显示的图片索引
hasStarted : false, //是否开始轮播
interval : null, //定时器
liItems : null, //要轮播的li元素集合
len : 0, //liItems的长度
aBox : null, //包含指示器的dom对象
bBox : null, //包含前后按钮的dom对象

/**
* 初始化及控制函数
* @param bannnerBox string 包含整个轮播图盒子的id或class
* @param aBox string 包含指示器的盒子的id或class
* @param btnBox string 包含前后按钮的盒子的id或class