微信小程序——左右滑動切換頁面

微信小程序——左右滑動切換頁面事件

微信小程序的左右滑動觸屏事件,主要有三個事件:touchstart,touchmove,touchend。
這三個事件最重要的屬性是pageX和pageY,表示X,Y坐標。
touchstart在觸摸開始時觸發事件;
touchend在觸摸結束時觸發事件;
touchmove觸摸的過程中不斷激發這個事件;
這三個事件都有一個timeStamp的屬性,查看timeStamp屬性,可以看到順序是touchstart => touchmove=> touchmove => ··· =>touchmove =>touchend。

第一步:在wxml文件中綁定事件(需要左右滑動的界面)

<view class="container" bindtouchstart="touchStart" bindtouchmove="touchMove" bindtouchend="touchEnd">
  // do something
</view>

第二步:在js文件中處理左右滑動邏輯

var touchDot = 0;//觸摸時的原點
var time = 0;//  時間記錄,用于滑動時且時間小于1s則執行左右滑動
var interval = "";// 記錄/清理 時間記錄
var nth = 0;// 設置活動菜單的index
var nthMax = 5;//活動菜單的最大個數
var tmpFlag = true;// 判斷左右華東超出菜單最大值時不再執行滑動事件

// 觸摸開始事件
touchStart:function(e){ 
   touchDot = e.touches[0].pageX; // 獲取觸摸時的原點
   // 使用js計時器記錄時間    
   interval = setInterval(function(){
       time++;
   },100); 
},
// 觸摸移動事件
touchMove:function(e){ 
   var touchMove = e.touches[0].pageX;
   console.log("touchMove:"+touchMove+" touchDot:"+touchDot+" diff:"+(touchMove - touchDot));
   // 向左滑動   
   if(touchMove - touchDot <= -40 && time < 10){
       if(tmpFlag && nth < nthMax){ //每次移動中且滑動時不超過最大值 只執行一次
           var tmp = this.data.menu.map(function (arr, index) {
               tmpFlag = false;
               if(arr.active){ // 當前的狀態更改
                   nth = index;
                   ++nth;
                   arr.active = nth > nthMax ? true : false;
               }
               if(nth == index){ // 下一個的狀態更改
                   arr.active = true;
                   name = arr.value;
               }
               return arr;
            })
           this.getNews(name); // 獲取新聞列表
           this.setData({menu : tmp}); // 更新菜單
       }
   }
   // 向右滑動
   if(touchMove - touchDot >= 40 && time < 10){
       if(tmpFlag && nth > 0){
           nth = --nth < 0 ? 0 : nth;
           var tmp = this.data.menu.map(function (arr, index) {
               tmpFlag = false;
               arr.active = false;
               // 上一個的狀態更改
               if(nth == index){
                   arr.active = true;
                   name = arr.value;
               }
               return arr;
           })
           this.getNews(name); // 獲取新聞列表
           this.setData({menu : tmp}); // 更新菜單
       }
   }
   // touchDot = touchMove; //每移動一次把上一次的點作為原點(好像沒啥用)
},
 // 觸摸結束事件
touchEnd:function(e){
   clearInterval(interval); // 清除setInterval
   time = 0;
   tmpFlag = true; // 回復滑動事件
},
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 13.1 事件流 “DOM2級事件”規定事件流包括3個階段:事件捕獲階段,處于目標階段,事件冒泡階段。事件捕獲表示...
    Elevens_regret閱讀 453評論 0 0
  • 基于html5的移動web頁面搭建技術總結 1.技術要點 1.1面向不同尺寸的手機屏幕,頁面布局適配問題。 網頁的...
    敲代碼的張閱讀 1,541評論 0 3
  • Web 瀏覽器中可能發生的事件有很多類型。如前所述,不同的事件類型具有不同的信息,而 DOM3 級事件規定了以下幾...
    More_5897閱讀 959評論 1 0
  • 原創微信公號:拍腦袋的發明 大部分情況下,一架永不落地的紙飛機需要這樣的高級技能: 精準的設計,準確的折紙,恰到好...
    光區閱讀 26,271評論 17 20
  • 本人承諾,文章內容為原創。 PART 1 古道旁,秋風四起,收韁停馬,看驍騎舊營,枯槁遍地,昔日熱血少年,如今提槍...
    流沙小妖怪閱讀 1,177評論 34 27