微信小程序没有自带的下拉菜单组件, 因此我们需要自己需要写一个
思路
利用列表来存储菜单项, 在外面套一个 view 元素作为外框, 将其设置为 overflow:hidden, 使用 CSS3 动画逐渐改变外层 view 元素的高度, 当高度为 0 时, 里面嵌套的列表元素被完全隐藏, 相当于菜单关闭. 而当 view 元素的高度大于列表元素的高度时, 相当于菜单显示.
效果图
wxml
button 按钮用于触发菜单的打开和关闭, first_click 参数使用户第一次点击按钮之前菜单不可见, state 参数用于控制菜单的打开和关闭状态
- <view id="text_box">
- <text decode='true'> 历 史 记 录 </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
- });
- }
- }
为了学习工作与休闲娱乐互不冲突, 现新建圈 [码农茶水铺] 用于程序员生活, 爱好, 交友, 求职招聘, 吐槽等话题交流, 希望各位大神工作之余到茶水铺来喝茶聊天. 群号: 582735936
来源: http://www.qdfuns.com/article/51116/1e2347c3a3b538b93c47d0231aece493.html