微信小程序實現左右滑動(帶動畫)

實例代碼

1 wxml

<view class="container1" wx:if="{{page == 1}}" bindtouchstart="touchStart" bindtouchmove="touchMove" bindtouchend="touchEnd" animation="{{ani1}}">
container1
</view>
<view class="container2" wx:if="{{page == 2}}"  bindtouchstart="touchStart" bindtouchmove="touchMove" bindtouchend="touchEnd" animation="{{ani2}}">
container2
</view>

js

const app = getApp()
var startX, endX;
var moveFlag = true;// 判斷執行滑動事件
Page({
  data: {
    page : 1,
    ani1: '',
    ani2: ''
  },
  onLoad: function () {
  },
  touchStart: function (e) {
    startX = e.touches[0].pageX; // 獲取觸摸時的原點
    moveFlag = true;
  },
  // 觸摸移動事件
  touchMove: function (e) {
    endX = e.touches[0].pageX; // 獲取觸摸時的原點
    if (moveFlag) {
      if (endX - startX > 50) {
        console.log("move right");
        this.move2right();
        moveFlag = false;
      }
      if (startX - endX > 50) {
        console.log("move left");
        this.move2left();
        moveFlag = false;
      }
    }
  },
  // 觸摸結束事件
  touchEnd: function (e) {
    moveFlag = true; // 回覆滑動事件
  },
  //向左滑動操作
  move2left() {
    var that = this;
    if (this.data.page == 2) {
      return
    }
    var animation = wx.createAnimation({
      duration: 1000,
      timingFunction: 'ease',
      delay: 100
    });
    animation.opacity(0.2).translate(-500, 0).step()
    this.setData({
      ani1: animation.export()
    })
    setTimeout(function () {
      that.setData({
        page: 2,
        ani2: ''
      });
    }, 800)
  },
  //向右滑動操作
  move2right() {
    var that = this;
    if (this.data.page == 1) {
      return
    }
    var animation = wx.createAnimation({
      duration: 1000,
      timingFunction: 'ease',
      delay: 100
    });
    animation.opacity(0.2).translate(500, 0).step()
    this.setData({
      ani2: animation.export()
    })
    setTimeout(function () {
      that.setData({
        page: 1,
        ani1: ''
      });
    }, 800)
    }
})

wxss

.container1 {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  padding: 200rpx 0;
  box-sizing: border-box;
  background-color: rgb(224, 118, 118)
}
.container2 {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  padding: 200rpx 0;
  box-sizing: border-box;
  background-color: wheat
}
page{
  height: 100%
}

說明

滑動切換頁面是根據判斷用戶在屏幕上的左右滑動操作,然後通過顯示和隱藏view實現。

動畫

(1)創建動畫實例

var animation = wx.createAnimation({
      duration: 1000,    //動畫時長
      timingFunction: 'ease',  //動畫的效果 
      delay: 100 //動畫延遲時間,單位 ms
    });

(2)動畫的動作

    animation.opacity(0.2).translate(-500, 0).step()
    //opacity動畫的透明, 範圍:0-1
    //translate(number tx, number ty)   tx 橫向移動,單位 px; ty 縱向移動,單位 px;

(3)將動畫綁定到元素

    this.setData({
      ani1: animation.export()
    })

微信小程序實現左右滑動

動畫·小程序

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章