当前位置: 首页 > 科技观察

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

时间:2023-03-19 12:43:50 科技观察

功能。默认情况下,它会无限循环地向右移动。单击数字可切换到相应的图片。所有图片重叠在布局上,即只要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)。3.step+14.如果moveWidth>图片宽度,执行第5步,否则requestAnimationFrame请求下一次执行,继续2-4。5、图片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].width;vargIndex=0;begainAnimate();//绑定左右点击事件oLeft.onclick=function(){clearTimeout(timeout);leftMove();begainAnimate();};oRight.onclick=function(){clearTimeout(timeout);rightMove();begainAnimate();};//绑定数字事件oButton.onclick=function(event){clearTimeout(timeout);vartargetEl=event.target;varnextIndex=(+targetEl.innerText)-1;console.log(nextIndex);rightMove(nextIndex);begainAnimate();}//默认初始动画向右移动functionbegainAnimate(){clearTimeout(timeout);timeout=setTimeout(function(){rightMove();begainAnimate();},3000);}//向左移动动画functionleftMove(){varnextIndex=(gIndex-1<0)?oImgs.length-1:gIndex-1;animateSteps(nextIndex,-50);}//移动动画函数rightMove(nextIndex){if(nextIndex==undefined){nextIndex=(gIndex+1>=oImgs.length)?0:gIndex+1;}animateSteps(nextIndex,50);}//一个动画函数animateSteps(nextIndex,timestamp){varcurrentImg=oImgs[gIndex];varnextImg=oImgs[nextIndex];nextImg.style.zIndex=10;varstep=0;requestAnimationFrame(goStep);//走一帧动画,移动时间戳函数goStep(){varmoveWidth=timestamp*step++;if(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);}css布局样式