40行代码 写个无限轮播图(低功耗)

167 阅读1分钟

支持手机和PC 只要看懂原理,直接帮代码复制到项目即可,以前也写过参考的swiper2版本代码有90多行, 其实没有40行 代码在缩进下30含就搞定,适合网站轮播图/内嵌上下视频滑动使用,再多数据不会卡顿

html 代码

  <div class="gallery" ref="swiper" style="position: relative;">
    <div class="image" style="position: absolute;">ONE</div>
    <div class="image" style="position: absolute;">TWO</div>
    <div class="image" style="position: absolute;">THREE</div>
  </div>
  • ref swiper 取到element对象即可
  • style 样式 position: relative;"position: absolute;
  • 美化按需求来aspect-ratio width overflow: hidden; cursor: grabbing; user-select: none;

轮播代码

const onSwiper = ()=>{
  let {swiper} = state;
  let {clientWidth} = swiper
  let [one,two,three] = swiper.childNodes
  let leep = [0,100,-100];
  let loop = [one,two,three];
  const onLoop = (diff=0) => (loop.forEach((item,key)=>{
    item.style.transform = `translate(${leep[key]-diff}%, 0px) translateZ(0px)`;
  }),false);
  // 初始一次
  let run = onLoop();
  // 主要逻辑
  const onMove = (MX)=>{
    if(run){
      let diff = ((run - MX) / clientWidth * 100) >> 0;
      if(Math.abs(diff) > 20){
        if(diff > 0){
          let pop = leep.pop();leep.unshift(pop);
        }else{
          let shift = leep.shift();leep.push(shift);
        }
        run = onLoop();
      }else{
        onLoop(diff);
      }
    }
  }
  // 开始
  swiper.onmousedown = ({clientX}) => run = clientX;
  swiper.ontouchstart = ({touches:[{clientX}]})=>run = clientX;
  // 移动
  swiper.ontouchmove = ({touches:[{clientX}]})=>onMove(clientX);
  swiper.onmousemove = ({clientX}) => onMove(clientX);
  // 结束
  swiper.ontouchend = ()=>run = onLoop();
  swiper.onmouseup = () => run = onLoop();
  swiper.onmouseleave = ()=>run = onLoop()
}
  • 多看几遍 解构取值的,代码跳来跳去的
  • 初始div就配置三个,Math.abs(diff) > 20偏移20px才跳转
  • 22行代码 这里应该应该弹出到你的处理函数
  • 在js的表达式(=>)中()叫圆括号运算符,从左往右算,并弹出最后一个

比如你是图片轮播

例如:记录 current % length +1 配和 v-for="item in list.splice(current,3)"

有个问题 我把transform: all 0.3s;关了,开动画的话他会从屏幕上划过,我忘了我以前咋处理的了,知道咋处理的,告诉我下

:::

前后端都写:南京/建邺区 求个萝卜坑 vx:micateam

:::