1. 程式人生 > 程式設計 >JS如何實現封裝列表右滑動刪除收藏按鈕

JS如何實現封裝列表右滑動刪除收藏按鈕

前言

  列表右滑動展示刪除和收藏按鈕就類似微信或者美團餓了嗎的列表,右滑動出現指定的按鈕功能;

  本來我是想把前幾年支付寶的一個機試題拿來講,奈何我記不太清題目,也找不到當時做的題了,所以只好將就一下那這個案例來講解,其實解題思路大致是一樣的,畢竟作為程式設計師最重要的不是會多少框架和會用api用的多熟練,設計思路才是最重要!

案例

JS如何實現封裝列表右滑動刪除收藏按鈕

  這個介面相信大家都非常熟悉,很多時候一些封裝好的外掛可以拿來用即可實現這個功能,算是比較大眾化,不過為了給不瞭解原理的小夥伴們講解,所以自己用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

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。