封装列表右滑动展示删除和收藏按钮

前言

  列表右滑动展示删除和收藏按钮就类似微信或者美团饿了吗的列表,右滑动出现指定的按钮功能;

  本来我是想把前几年支付宝的一个机试题拿来讲,奈何我记不太清题目,也找不到当时做的题了,所以只好将就一下那这个案例来讲解,其实解题思路大致是一样的,毕竟作为程序员最重要的不是会多少框架和会用api用的多熟练,设计思路才是最重要!

案例

  

   这个界面相信大家都非常熟悉,很多时候一些封装好的插件可以拿来用即可实现这个功能,算是比较大众化,不过为了给不了解原理的小伙伴们讲解,所以自己用dom手写了一个,思路如下:

html部分

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport"
    content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <title>支付宝前端机试题</title>
  <link rel="stylesheet" href="css/index.css">
  <script src="js/index.js"></script>
</head>

<body>
  <h2 class="title">购物车</h2>
  <section class="shoppingList"></section>
</body>

</html>

JS部分

let initXY = [0,0];//记录移动的坐标
let isStop = false;//记录是否禁止滑动
let oldIndex = null;//记录旧的下标
let theIndex = null;//记录新的下标

function touchstart(event,index){
  if(event.touches.length > 1) {
    isStop = true;
    return;
  }
  oldIndex = theIndex;
  theIndex = null;
  initXY = [event.touches[0].pageX,event.touches[0].pageY];
  // console.log(initXY);
}

function touchmove(event,index){
  if(event.touches.length > 1) return;
  let moveX = event.touches[0].pageX - initXY[0];
  let moveY = event.touches[0].pageY - initXY[1];
  if(isStop || Math.abs(moveX) < 5) return;//如果禁止滑动或者滑动的距离小于5就返回
  if(Math.abs(moveY) > Math.abs(moveX)){
    isStop = true;
    return;
  }
  if(moveX<0){
    theIndex = index;
    isStop = true;
  }else if(theIndex && oldIndex === theIndex){
    oldIndex =index;
    theIndex = null;
    isStop = true;
    setTimeout(()=>{oldIndex=null;},150);//设置150毫秒延迟来凸显动画效果,实际不加也可以
  }
  // 这里用jq就不用循环了,但我懒得引,大家知道就好
  let goods = document.getElementsByClassName("goodsInfo");
  for(let i=0;i<goods.length;i++){
    theIndex === i ? goods[i].classList.add("open") : goods[i].classList.remove("open");
  };
  // console.log(moveX,moveY);
}

function touchend(){
  isStop = false;
}

总结

  实现的方法无非就是判断触碰的时候移动的坐标值再加上动画,有兴趣看源代码的小伙伴可以到github下载:https://github.com/13632756286/Sliding-menu

原文地址:https://www.cnblogs.com/zxd66666/p/13221953.html