JS如何實(shí)現(xiàn)封裝列表右滑動刪除收藏按鈕
前言
列表右滑動展示刪除和收藏按鈕就類似微信或者美團(tuán)餓了嗎的列表,右滑動出現(xiàn)指定的按鈕功能;
本來我是想把前幾年支付寶的一個機(jī)試題拿來講,奈何我記不太清題目,也找不到當(dāng)時做的題了,所以只好將就一下那這個案例來講解,其實(shí)解題思路大致是一樣的,畢竟作為程序員最重要的不是會多少框架和會用api用的多熟練,設(shè)計(jì)思路才是最重要!
案例
這個界面相信大家都非常熟悉,很多時候一些封裝好的插件可以拿來用即可實(shí)現(xiàn)這個功能,算是比較大眾化,不過為了給不了解原理的小伙伴們講解,所以自己用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>支付寶前端機(jī)試題</title> <link rel='stylesheet' href='http://m.cgvv.com.cn/bcjs/css/index.css' rel='external nofollow' > <script src='http://m.cgvv.com.cn/bcjs/js/index.js'></script></head><body> <h2 class='title'>購物車</h2> <section class='shoppingList'></section></body></html>
JS部分
let initXY = [0,0];//記錄移動的坐標(biāo)let isStop = false;//記錄是否禁止滑動let oldIndex = null;//記錄舊的下標(biāo)let theIndex = null;//記錄新的下標(biāo)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);//設(shè)置150毫秒延遲來凸顯動畫效果,實(shí)際不加也可以 } // 這里用jq就不用循環(huán)了,但我懶得引,大家知道就好 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;}
總結(jié)
實(shí)現(xiàn)的方法無非就是判斷觸碰的時候移動的坐標(biāo)值再加上動畫,有興趣看源代碼的小伙伴可以到github下載:
https://github.com/13632756286/Sliding-menu
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. php使用正則驗(yàn)證密碼字段的復(fù)雜強(qiáng)度原理詳細(xì)講解 原創(chuàng)2. 基于javaweb+jsp實(shí)現(xiàn)企業(yè)車輛管理系統(tǒng)3. HTML5實(shí)戰(zhàn)與剖析之觸摸事件(touchstart、touchmove和touchend)4. ASP將數(shù)字轉(zhuǎn)中文數(shù)字(大寫金額)的函數(shù)5. Jsp servlet驗(yàn)證碼工具類分享6. jscript與vbscript 操作XML元素屬性的代碼7. 基于PHP做個圖片防盜鏈8. Jsp+Servlet實(shí)現(xiàn)文件上傳下載 文件列表展示(二)9. asp.net core 認(rèn)證和授權(quán)實(shí)例詳解10. XML在語音合成中的應(yīng)用
