微信小程序CSS3动画下拉菜单

微信小程序没有自带的下拉菜单组件,因此我们需要自己需要写一个

思路

利用列表来存储菜单项,在外面套一个view元素作为外框,将其设置为overflow:hidden,使用CSS3动画逐渐改变外层view元素的高度,当高度为0时,里面嵌套的列表元素被完全隐藏,相当于菜单关闭。而当view元素的高度大于列表元素的高度时,相当于菜单显示

效果图

这里写图片描述

wxml
button按钮用于触发菜单的打开和关闭,first_click参数使用户第一次点击按钮之前菜单不可见,state参数用于控制菜单的打开和关闭状态

<view id="text_box">
      <text decode='true'>&nbsp;历&nbsp;史&nbsp;记&nbsp;录</text>
</view>
<button id="slide" bindtap="toggle"></button>
<view id="box" class="{{first_click?'show':'hide'}} {{state?'open':'close'}}">
      <view id="item_list">
            <view>111</view>
            <view>222</view>
            <view>333</view>
      </view>
</view>

css
使用@keyframes动画实现菜单的渐变打开和关闭动画

#box{
  width: 100%;
  border-top: 1px solid #ddd;
  overflow: hidden;
  height: 0;
  animation-fill-mode: forwards;
}

#item_list{
    background-color: white;
    width: 100%;
}

#item_list view{
    text-align: right;
    overflow: auto;
    white-space: nowrap;
}

@keyframes slidedown{
    from {
        height: 0;
    }
    to {
        height: 240rpx;
    }
}

@keyframes slideup{
    from {
        height: 240rpx;
    }
    to {
        height: 0;
    }
}

.open{
    animation: slidedown 1s;
}

.close{
    animation: slideup 1s; 
}

.hide{
    display: none;
}

.show{
    display: block;
}

js
页面加载完成时,菜单初始状态为隐藏和关闭,用户一旦点击按钮,菜单就显示,并逐渐打开

data: {
    state:false,
    first_click:false,
  },

 toggle: function(){
      var list_state = this.data.state,
          first_state = this.data.first_click;
      if (!first_state){
          this.setData({
            first_click: true
          });
      }
      if (list_state){
          this.setData({
            state: false
          });
      }else{
          this.setData({
            state: true
          });
      }
  }

猜你喜欢

转载自blog.csdn.net/zjw_python/article/details/80720427