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

NativeJS使用transform实现banner的无限滚动

时间:2023-04-02 14:28:56 HTML

功能。默认情况下,无限循环向右移动。单击数字可切换到相应的图片。点击左右切换图片。所有图片重叠在布局上,即只要Y方向对齐,当前可见的图片z-index级别最高。每3s换一张图片,用setTimeout计时。使用gIndex记录当前可见区域显示的图片的下标,每次变化时计算下一张图片的下标。通过requestAnimationFrame实现一个图片切换的动画。这种方法也可以让整个页面始终只有2个img标签,而不需要创建所有的img节点。重点是每次都要更换不可见img的src。动画的实现首先定义一个时间戳,记录每一帧移动了多少距离。定义初始step=0,记录移动步数。每次移动的距离moveWidth为timestamp*step,图1向右移动增加moveWidth,图2从左侧进入moveWidth。因此,图像1的变换是translate(moveWidth),图像2的变换是translate(moveWidth-imagewidth)。step+1如果moveWidth>图片宽度,转第5步,否则requestAnimationFrame请求下一次执行,继续2-4。图片1和2都放在起始位置,图片2的z-index设置为最高。这样就完成了一个移动动画。html代码

1
2
3
4
JS代码vartimeout=null;window.onload=function(){varoLeft=document.querySelector('.left');varoRight=document.querySelector('.right');varoButton=document.querySelector('.buttons');varoButtons=document.querySelectorAll('.buttonsdiv');varoImgs=document.querySelectorAll('.boximg');varimgWidth=oImgs[0]。宽度;变量gIndex=0;开始动画();//绑定左右点击事件oLeft.onclick=function(){clearTimeout(timeout);左移动();开始动画();};oRight.onclick=function(){clearTimeout(超时);右移();开始动画();};//绑定数字序列号eventoButton.onclick=function(event){clearTimeout(timeout);vartargetEl=event.target;varnextIndex=(+targetEl.innerText)-1;控制台日志(下一个索引);右移(下一个索引);开始动画();}//默认初始动画到右边functionbeginAnimate(){clearTimeout(timeout);timeout=setTimeout(function(){rightMove();beginAnimate();},3000);}//动画向左移动functionleftMove(){varnextIndex=(gIndex-1<0)?oImgs.length-1:gIndex-1;animateSteps(nextIndex,-50);}//向右移动动画functionrightMove(nextIndex){if(nextIindex==undefined){nextIndex=(gIndex+1>=oImgs.length)?0:g索引+1;}animateSteps(nextIndex,50);}//一次动画functionanimateSteps(nextIndex,timestamp){varcurrentImg=oImgs[gIndex];varnextImg=oImgs[nextIndex];nextImg.style.zIndex=10;可变步骤=0;requestAnimationFrame(goStep);//走一杠的动画,移动timestampfunctiongoStep(){varmoveWidth=timestamp*step++;如果(Math.abs(moveWidth)0?(moveWidth-imgWidth):(imgWidth+moveWidth)}px)`;requestAnimationFrame(goStep);}else{currentImg.style.zIndex=1;currentImg.style.transform=`translate(0px)`;nextImg.style.transform=`translate(0px)`;oButtons[gIndex].setAttribute('class','');oButtons[nextIndex].setAttribute('class','active');gIndex=nextIndex;}}}}window.onclose=function(){clearTimeout(timeout);}csslayoutstyle