微信小程序自定义弹窗,实现底部弹出动画

使用到:Animation

组件popup

  • 路径components/popup
  • popup.wxml
点击查看代码
<!--components/popup.wxml-->
<view class="box" hidden="{{!isShow}}">
  <view class="empty-box" bindtap="hideModal" id="empty-box"></view>
  <view class="content" animation="{{animate}}">
    <view class="f-title jcsb">
      标题 <text class="iconfont icon-close" bindtap='hideModal'></text>
    </view>
    <view class="f-context">内容</view>
    <button class="btn" bindtap="confirm" type="warn">按钮</button>
  </view>
</view>
  • popup.wxss
点击查看代码
/* components/popup.wxss */
.box {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1000;
  width: 100vw;
  height: 100vh;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  flex-direction: column;
}
.empty-box {
  flex: 1;
  background-color: transparent;
}
.content {
  width: 100vw;
  max-height: 90vh;
  padding: 30rpx 30rpx 140rpx;
  box-sizing: border-box;
  background: rgba(255, 255, 255, 1);
  opacity: 1;
  border-radius: 14rpx 14rpx 0px 0px;
  z-index: 100;
}
.f-context{
  height: 800rpx;
  text-align: center;
}
.btn{
  position: absolute;
  bottom: 40rpx;
  left: 0;
  right: 0;
}
  • popup.js
点击查看代码
// components/popup.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    show: {
      type: Boolean,
      value: false
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    animate: {},
    isShow: false,
  },

  /**
   * 数据监听
   */
  observers: {
    'show': function (val) {
      val ? this.showModal() : this.hideModal()
    }
  },
  /**
   * 组件的方法列表
   */
  methods: {
    // 显示遮罩层
    showModal() {
      this.setData({
        isShow: true
      })
      const animation = wx.createAnimation({
        duration: 500,
        timingFunction: 'ease'
      })
      // 先显示背景再执行动画,translateY(0)偏移量为0代表显示默认高度
      setTimeout(() => {
        animation.translateY(0).step()
        this.setData({
          animate: animation.export()
        })
      }, 50)

    },
    // 隐藏遮罩层
    hideModal() {
      const animation = wx.createAnimation({
        duration: 500,
        timingFunction: 'ease',
      })
      // 设置为100vh可以确保滚动到底部,可以按照自己的内容高度设置,能够滑到底部即可
      animation.translateY('100vh').step()
      this.setData({
        animate: animation.export(),
      })
      // 先执行动画,再隐藏组件
      setTimeout(() => {
        this.setData({
          isShow: false
        })
      }, 500)
    },
    // 确认
    confirm() {
      this.hideModal()
    },
  }
})

引用组件

  • index.json
点击查看代码
{
  "usingComponents": {
    "popup": "../../components/popup/popup"
  }
}
  • index.wxml
点击查看代码
<!--index.wxml-->
<view class="container">
  <button type="primary" catchtap="showPopup">显示</button>
  <popup show="{{isShowPopup}}" />
</view>
  • index.js
点击查看代码
// index.js
Page({
  data: {
    isShowPopup: false
  },
  showPopup(){
    this.setData({
      isShowPopup: true
    })
  }
})
posted @ 2022-06-02 14:09  怀揣着梦想  阅读(1788)  评论(0)    收藏  举报