1. 程式人生 > >小程式之解決移動端點選和長按事件冒泡問題

小程式之解決移動端點選和長按事件冒泡問題

      如果我們希望一個物件被長按的時候不會觸發點選事件,如果你同時繫結上bindtap事件和bindlongtap事件的話這裡會有一個問題就是不管你有沒有點選,長按的時候就會觸發點選事件,我們有一個需求就是在點選的時候跳轉頁面,但是在長按的時候刪除某個物件。

     所以這個時候我們就要考慮自己封裝了

     wxml

<image class="book-image" src="{{item.img_path}}" mode="scaleToFill" bindtouchstart="mytouchstart" bindtouchend="mytouchend" catchtap="toDetail" hidden="{{isShow}}"  data-goodId="{{item.goods_id}}" ></image>

  .js
  toDetail:function(options){
    let that = this;
    //觸控時間距離頁面開啟的毫秒數
    var touchTime = that.data.touch_end - that.data.touch_start;
    console.log(touchTime);
    var goodId=options.target.dataset.goodid;
    if(touchTime<350){
      console.log(goodId)
      var goodUrl='../book-detail/book-detail?bookid='+goodId;
      wx.navigateTo({
        url:goodUrl
      });
    }else{
      this.setData({
        isShow:true
      })
    }

  },
  
mytouchstart: function (e) {
    let that = this;
    that.setData({
      touch_start: e.timeStamp
    })
    console.log(e.timeStamp + '- touch-start')
  },
  //按下事件結束
  mytouchend: function (e) {
    let that = this;
    that.setData({
      touch_end: e.timeStamp
    })
    console.log(e.timeStamp + '- touch-end')
  },


  原理就是利用e.timeStamp來獲取start和end之間的時間間隔,然後根據不同的時間間隔來實現不同的效果,是不是很簡單!!!!!·~~~~~~~