JS如何实现封装列表右滑动删除收藏按钮
导读:前言列表右滑动展示删除和收藏按钮就类似微信或者美团饿了吗的列表,右滑动出现指定的按钮功能;本来我是想把前几年支付宝的一个机试题拿来讲,奈何我记不太清题目,也找不到当时做的题了,所以只好将就一下那这个案例来讲解,其实解题思路大致是一样的,毕竟作为程序员最重要的不是会多少框架和会用api用的多熟练,设计...
前言
列表右滑动展示删除和收藏按钮就类似微信或者美团饿了吗的列表,右滑动出现指定的按钮功能;
本来我是想把前几年支付宝的一个机试题拿来讲,奈何我记不太清题目,也找不到当时做的题了,所以只好将就一下那这个案例来讲解,其实解题思路大致是一样的,毕竟作为程序员最重要的不是会多少框架和会用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='https://www.haobala.com/bcjs/css/index.css' rel='external nofollow' > <script src='https://www.haobala.com/bcjs/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
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持好吧啦网。
相关文章:
1. CSS3实例分享之多重背景的实现(Multiple backgrounds)2. intellij idea中spring boot properties文件不能自动提示问题解决3. Android自定义Dialog框样式4. 使用Canal实现PHP应用程序与MySQL数据库的实时数据同步5. 一篇文章带你了解JavaScript-语句6. 详解IDEA搭建springBoot方式一(推荐)7. asp.net core服务限制堆内存大小的操作方法8. intellij idea写Python教程9. Android Studio导入jar包过程详解10. IntelliJ IDEAx导出安卓(Android)apk文件图文教程