JQuery写的一个常见的banner
大致的布局如下:
<div class="banner" >
<div class="pic">
<ul>
<li><img src="img/banner4.jpg" alt="" /></li>
<li><img src="img/banner1.png" alt="" /></li>
<li><img src="img/banner2.png" alt="" /></li>
<li><img src="img/banner3.jpg" alt="" /></li>
<li><img src="img/banner4.jpg" alt="" /></li>
<li><img src="img/banner1.png" alt="" /></li>
</ul>
</div>
<!--点播列表-->
<div class="tab">
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
<!--banner 两边的按钮-->
<div class="btn">
<div id="left"> < </div>
<div id="right"> > </div>
</div>
</div>
css样式如下:
.banner{width:100%;height:400px;position:relative;}
.banner .pic{width: 100%;height: 100%;overflow: hidden;}
.banner .pic ul{width: 1000%;height: 100%;margin-left: -100%;}
.banner .pic ul li{width: 10%;height: 100%;float: left;}
.banner .pic ul li img{width: 100%;height: 100%;}
.banner .tab{width: 136px;height: 3px;position: absolute;bottom: 20px;left: 50%;margin-left: -68px;}
.banner .tab ul li{width: 30px;height: 3px;float: left;margin: 0 2px;background: #5D5C60;}
.banner .tab ul li.on{background: #0DA1A4;}
.banner .btn div{width: 30px;height: 40px;background: rgba(0, 0, 0, 0.5);font-size:20px;text-align: center;line-height: 40px;color: #fff;position: absolute;top: 50%;margin-top: -20px;display: none;}
#left{left: 15px;}
#right{right: 15px;}
JS代码:
~function(){
var banner = $('.banner');
var picUl = $('.banner .pic ul');
var tabLi = $('.banner .tab ul li');
var btnDiv = $('.banner .btn div');
var width = banner.width();
var index = 0;
var timer = null;
var nowTime = 0;
//底部Li列表添加on样式
tabLi.eq(0).addClass('on');
setAuto();
tabLi.click(function(){
index = $(this).index();
tabLi.eq(index).addClass('on').siblings().removeClass('on');
picUl.stop().animate({
marginLeft:-width*(index+1)+'px'
},1000);
});
btnDiv.click(function(){
if (new Date() - nowTime >500) {
nowTime = new Date();
var i = $(this).index();
i?index++:index--;
change();
}
});
function setAuto(){
timer = setInterval(function(){
index++;
change();
},5000);
};
banner.hover(function(){
btnDiv.show(1000);
clearInterval(timer);
},setAuto).mouseleave(function(){
btnDiv.hide(1000);
});
function change(){
index >= tabLi.length?tabLi.eq(0).addClass('on').siblings().removeClass('on'):tabLi.eq(index).addClass('on').siblings().removeClass('on');
picUl.stop().animate({
marginLeft:-width*(index+1)+'px'
},1000,function(){
if (index==4) {
index = 0;
picUl.css("marginLeft",-width+'px');
} else if(index == -1){
index = tabLi.length - 1;
picUl.css("marginLeft",-width*(index+1)+'px');
}
});
}
}();
作为一个新手,用两天时间调试的banner图,感觉还是可以的~_~~_~