APP + H5 開發,仿照ios體驗,實現右滑返回上一頁


目前開發一個項目,主要用app殼子,內部全部使用H5開發

看到ios中右滑返回上一頁的體驗性比較好,想在h5中實現

思考一下有幾點需要注意:

1.這個監聽事件不能在每個子頁面下添加,需要在父頁面(app.vue)上添加

2.滑動的監聽事件:  touchstart,touchmove

3.不能太過靈敏,需要滑動一段距離后,觸發返回上一頁,否則再點擊頁面事件會有沖突

<template>
  <div id="app" @touchstart="touchstartApp" @touchmove="touchmoveApp">
    <router-view :key="$route.fullPath" />
  </div>
</template>
  startX: number = 0;
  startY: number = 0;
  moveEndX: number = 0;
  moveEndY: number = 0;

  touchstartApp(e: any) {
    (this.startX = e.targetTouches[0].pageX), (this.startY = e.targetTouches[0].pageY);
  }

  touchmoveApp(e: any) {
    this.moveEndX = e.targetTouches[0].pageX;
    this.moveEndY = e.targetTouches[0].pageY;
    const X = this.moveEndX - this.startX;
    const Y = this.moveEndY - this.startY;
    if (Math.abs(X) > Math.abs(Y) && X > 100) { // 右滑超出一段距離
      if(!sesStorage.getItem('touchmovePro')){
        router.go(-1)
      }
      console.log('left 2 right');
    } else if (Math.abs(X) > Math.abs(Y) && X < 0) {
      // console.log('right 2 left');
    } else if (Math.abs(Y) > Math.abs(X) && Y > 0) {
      // console.log('top 2 bottom');
    } else if (Math.abs(Y) > Math.abs(X) && Y < 0) {
      // console.log('bottom 2 top');
    } else {
      // console.log('just touch');
    }
    sesStorage.removeItem('touchmovePro')
  }

添加完了既可以了,但是我發現頁面有需要橫向滑動的功能

這樣的話,每次想要橫向滑動的時候,頁面就會返回

 

想到一個思路,通過開關思想:當需要左右滑動的功能里添加一個屬性,在監聽滑動是否返回上一頁那塊取值,判斷是否有這個屬性,只要有就不執行返回上一頁這個操作

// 需要滑動的組件
<div class="banner_box" id="tabBox" @touchmove="touchmovePro">
    <ul>
        <li
            class="banner_item"
            :class="{bannerActive:index == bannerChooseIndex}"
            @click="bannerEvt(item,index)"
            v-for="(item,index) in bannerList"
            :key="index"
        >
            <span>{{item.value}}</span>
        </li>
    </ul>
 </div>


touchmovePro(){
    sesStorage.setItem('touchmovePro',true)
  }

  

我只通過 sessionStorage 存取值, 當然要在最后清除這個屬性 sesStorage.removeItem('touchmovePro'),防止只要操作左右滑動的功能,就失去優化返回的功能

在哪里進行刪除呢,通過冒泡原理,在它的父組件 touchmove事件中刪除,這樣就實現了,每次操作完左右滑動的功能,及時刪除

 

之前有想過一個思路:阻止事件冒泡,但是,在不需要阻止的地方,有需要放開,這樣添加的事件就多了,比較麻煩,還是目前這樣解決較為簡單

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM