欢迎来到代码驿站!

当前位置:首页 >

JS如何实现封装列表右滑动删除收藏按钮

时间:2020-07-23 14:01:00|栏目:|点击:

前言

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

  本来我是想把前几年支付宝的一个机试题拿来讲,奈何我记不太清题目,也找不到当时做的题了,所以只好将就一下那这个案例来讲解,其实解题思路大致是一样的,毕竟作为程序员最重要的不是会多少框架和会用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" rel="external nofollow" >
 <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

上一篇:git stash暂存的操作方法

栏    目:

下一篇:R语言ggplot2边框背景去除的实现

本文标题:JS如何实现封装列表右滑动删除收藏按钮

本文地址:http://www.codeinn.net/misctech/2464.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有