jquery无缝图片轮播组件封装
图片轮播在我们的前端开发中是非常常见的,下面是自己写的一个图片轮播组件,支持自动轮播,手动轮播,无缝衔接。
dom结构
首先是dom结构,将所有内容放入一个大盒子,应用ul标签存放图片列表,圆点定位图片位置。
<
图片轮播在我们的前端开发中是非常常见的,下面是自己写的一个图片轮播组件,支持自动轮播,手动轮播,无缝衔接。
dom结构
首先是dom结构,将所有内容放入一个大盒子,应用ul标签存放图片列表,圆点定位图片位置。
<
下面是盒子样式,这里使用百分比自适应,大盒子使用overflow:hidden;防止图片溢出,将ul宽设置为图片总宽度+1(这里+1后面会有用到)。
#box{
width:100%;
height:40.0em;
overflow:hidden;
position:absolute;
}
#box#banners{
width:500%;
position:relative;
}
#box.banners-img{
float:left;
width:20%;
height:40.0em;
}
#box.banners-imgimg{
width:100%;
height:100%;
}
.num{
width:10%;
height:2.0em;
position:relative;
top:82%;
left:40%;
-webkit-transform:rotate(-90deg);
-ms-transform:rotate(-90deg);
transform:rotate(-90deg);
}
.numli{
width:2.0em;
height:100%;
position:relative;
border-radius:50%;
background-color:grey;
}
.num.on{
background-color:black;
}
.btns{
width:1.0em;
height:1.0em;
background-color:rgba(0,0,0,0.5);
position:relative;
top:50%;
color:white;
font-size:3.0em;
text-align:center;
line-height:1.0em;
cursor:pointer;
display:none;
}
#box:hover.btns{
display:block;
}
.btn_l{
left:0;
}
.btn_r{
right:0;
}
组件使用jquery编写
functionaddImg(item,arrSrc){//添加图片,这里需同时修改样式,读者可自行修改
for(leti=0;i- ");
}
//获取图片宽度
varimgWidth=parseInt($("#banners.banners-img").css("width"));
//因宽度为百分比,窗口大小变化时需重新获取
window.onresize=function(){
varnewWidth=$("#banners.banners-img").css("width");
imgWidth=parseInt(newWidth);
}
//鼠标移到按钮时轮播
$(".numli").hover(function(){
varindex=$(this).index();
i=index;
$("#box#banners").stop().animate({left:-i*imgWidth},500);
$("#box.numli").eq(i).addClass("on")
.siblings().removeClass("on");
})
//自动轮播
vart=setInterval(function(){
i++;
move();
},3000);
//鼠标移入时停止自动轮播
$("#box").hover(function(){
clearInterval(t);
},function(){
t=setInterval(function(){
i++;
move();
},3000);
})
//手动轮播
$("#box.btn_l").click(function(){
i--;
move();
});
$("#box.btn_r").click(function(){
i++;
move();
});
//封装一个运动函数
//alert(imgWidth);
functionmove(){
if(i==Size){//当轮播到最后一张时过渡到第一张图片
$("#box#banners").css({left:0});
i=1;
}
if(i==-1){
$("#box#banners").css({left:-(Size-1)*imgWidth});
i=Size-2;
}
$("#box#banners").stop().animate({left:-i*imgWidth},500);
if(i==Size-1){
$("#box.numli").eq(0).addClass("on")
.siblings().removeClass("on");
}else{
$("#box.numli").eq(i).addClass("on")
.siblings().removeClass("on");
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。