1. 程式人生 > >【微信小程式】自定義抽屜式選單(底部,從下向上拉出)

【微信小程式】自定義抽屜式選單(底部,從下向上拉出)

微信提供了動畫api,就是下面這個


通過使用這個建立動畫的api,可以做出很多特效出來

下面介紹一個抽屜選單的案例

實現程式碼:

wxml:

<!--button-->
<view class="btn" bindtap="powerDrawer" data-statu="open">button</view>
<!--mask-->
<view class="drawer_screen" bindtap="powerDrawer" data-statu="close" wx:if="{{showModalStatus}}"></view>
<!--content-->
<!--使用animation屬性指定需要執行的動畫-->
<view animation="{{animationData}}" class="drawer_attr_box" wx:if="{{showModalStatus}}">
  <!--drawer content-->
  <view class="drawer_content">
    <view class="drawer_title line">選單1</view>
    <view class="drawer_title line">選單2</view>
    <view class="drawer_title line">選單3</view>
    <view class="drawer_title line">選單4</view>
    <view class="drawer_title">選單5</view>
  </view>
</view>

wxss

/*button*/
.btn {
  width: 80%;
  padding: 20rpx 0;
  border-radius: 10rpx;
  text-align: center;
  margin: 40rpx 10%;
  background: #0C1939;
  color: #fff;
}
/*mask*/
.drawer_screen {
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 1000;
  background: #000;
  opacity: 0.2;
  overflow: hidden;
}
/*content*/
.drawer_attr_box {
  width: 100%;
  overflow: hidden;
  position: fixed;
  bottom: 0;
  left: 0;
  z-index: 1001;
  background: #fff;
}
.drawer_content {
  padding: 20rpx 40rpx;
  height: 470rpx;
  overflow-y: scroll;
}
.drawer_title{
  padding:20rpx;
  font:42rpx "microsoft yahei";
  text-align: center;
}
.line{
  border-bottom: 1px solid #f8f8f8;
}

js

Page({
  data: {
    showModalStatus: false
  },
  powerDrawer: function (e) {
    var currentStatu = e.currentTarget.dataset.statu;
    this.util(currentStatu)
  },
  util: function(currentStatu){
    /* 動畫部分 */
    // 第1步:建立動畫例項 
    var animation = wx.createAnimation({
      duration: 200,  //動畫時長
      timingFunction: "linear", //線性
      delay: 0  //0則不延遲
    });
    
    // 第2步:這個動畫例項賦給當前的動畫例項
    this.animation = animation;

    // 第3步:執行第一組動畫:Y軸偏移240px後(盒子高度是240px),停
    animation.translateY(240).step();

    // 第4步:匯出動畫物件賦給資料物件儲存
    this.setData({
      animationData: animation.export()
    })
    
    // 第5步:設定定時器到指定時候後,執行第二組動畫
    setTimeout(function () {
      // 執行第二組動畫:Y軸不偏移,停
      animation.translateY(0).step()
      // 給資料物件儲存的第一組動畫,更替為執行完第二組動畫的動畫物件
      this.setData({
        animationData: animation
      })
      
      //關閉抽屜
      if (currentStatu == "close") {
        this.setData(
          {
            showModalStatus: false
          }
        );
      }
    }.bind(this), 200)
  
    // 顯示抽屜
    if (currentStatu == "open") {
      this.setData(
        {
          showModalStatus: true
        }
      );
    }
  }
})