当前位置: 首页 > Web前端 > CSS

一种无缝轮播的方法原理

时间:2023-03-31 10:56:55 CSS

之前面试的时候被问到这个问题。以前都是随便找大神的插件,知道怎么做,但是一直没有实现。无缝轮播的原理是在滚动层前后分别插入last元素和front元素,然后在动画滚动到末尾或最前面时初始化滚动层的位置样式,速度快,检测不到,就像无缝一般。html片段

css样式.wrap{width:620px;高度:413px;溢出:隐藏;位置:固定;顶部:0;左:0;底部:0;右:0;保证金:自动;边框:5px实心#FFF;背景:#FFF;}ul{宽度:自动;位置:绝对;顶部:0;左:0;}li{宽度:620px;高度:413px;向左飘浮;列表样式:无;框大小:边框框;border:5pxsolid#E0E0E0;}img{width:100%;}a{display:block;宽度:50px;高度:20px;背景:#CCC;颜色:#FFF;字体大小:14pX;文本对齐:居中;位置:绝对;z-指数:9;文本装饰:无;}a:第一个类型{顶部:50%;左:10px;transform:translateY(-50%);}a:last-of-type{top:50%;右:10px;转换:translateY(-50%);}JS$(document).ready(function(){letindex=1,instance=$('li')[0].offsetWidth,oldlen=$('li').length;//在$('ul').append($("li").eq(0).clone()).prepend($("li").eq前后分别插入最后一个元素和前面一个元素(oldlen-1).clone());;让len=$('li').length;$('ul').css({'width':instance*len+'px','left':-instance+'px'});$('.nextBtn').on('click',function(){index++;$('ul').stop().animate({'left':-instance*index},300,function(){//当滑动到末尾时(复制到末尾第一张图片的位置),动画完成后,初始化整个图片滚动层容器的位置if(index==len-1){index=1;$('ul').css({'left':-instance*index+'px'});}});});$('.prevBtn').on('点击',函数(){索引--;$('ul').stop().animate({'left':-instance*index},300,function(){//当滑动到最前面时(复制到最后一张图片的最前面位置),之后动画完成,初始化整个图片滚动层容器的位置if(index==0){index=len-2;$('ul').css({'left':-instance*index+'px'});}});});//自动播放函数autoPlay(){autoplay=setInterval(function(){index++;$('ul').stop().animate({'left':-instance*index},300,function(){if(index==len-1){index=1;$('ul').css({'left':-instance*index+'px'});}});},3000);};自动播放();$('.wrap').hover(function(){autoplay&&clearInterval(autoplay);},function(){autoPlay();});});注意没有加入轮播索引,这个比较容易,只需要注意索引的值即可