微信小程序-侧边栏-获取用户选中的值

侧边栏是APP中很常见的一种功能,最近公司的微信小程序项目刚好需要侧边栏这个功能,抱着能自己写就自己写的工作态度,所以决定用基础一些技术来完成此功能。

一、WXML

<view class='body'>
  <view class="leftBox '{{leftView?'leftActive':''}}'" bindtap='getLeft' data-item="1">
    <view class="left '{{leftView?'leftActive':''}}'" catchtap='getleft'>
      <view class='infolist'>
        <text wx:for="{{items}}" wx:key="{{*this}}" data-item="{{index}}" 
        catchtap='getChecked' class="{{item.userChecked?'userActive':''}}">{{item.value}}</text>
      </view> 
      <button class='clear' catchtap='getClear'>清空选择</button>
    </view>
  </view>
  <button catchtap='getLeft' class='button'>显示侧边栏</button>
</view>

二、WXSS

/*主体  */
.body{
  width:100vw;
  height:100vh;
  background:#ccc;
  position:relative;
}
.leftBox{
  width:100vw;
  height:100vh;
  background:rgba(0,0,0,.5);
  position:fixed;
  right:-1000px;
  top:0px;
  z-index:1;
}
.left{
  width:80vw;
  height:100vh;
  background:#fff;
  position:fixed;
  right:-1000px;
  top:0px;
   transition: all .5s;/*动画  */ 
  z-index:10;
}
.leftActive{
  right:0px;
}
/*列表  */
.infolist{
  width:100%;
}
.infolist text{
  display:inline-block;
  padding:10px;
  margin:5px;
  border-radius:4px;
  background:#eee;
}
.infolist .userActive{
  background:red;
  color:#fff;
}
/*清空  */
.clear{
  width:100px;
  height:40px;
  border-radius:4px;
  line-height:40px;
  background:#eee;
  text-align:center;
  position:absolute;
  bottom:10px;
  left:50%;
  transform: translateX(-50%);
}

/*按钮  */
.button{
  display:inline-block;
  width:100vw;
  height:40px;
  margin-top:10px;
}

三、JS

Page({
  data: {
    leftView:false,
    userChecked:false,
    items:[
      {value:'社会'},
      {value:'生活'},
      {value:'教育'},
      {value:'音乐'}
    ],
  },

  //侧边栏显示和隐藏
  getLeft:function(e){
    let prent = e.target.dataset.item;
    let left = this.data.leftView;
    if (left){
      this.data.leftView = false;
    }else{
      this.data.leftView = true;
    }
    this.setData({ leftView: this.data.leftView})
  },

  getleft:function(e){
    
  },

  //用户选中的值
  getChecked:function(e){
    let index = e.target.dataset.item;
    let checked = this.data.items;
    if (checked[index].userChecked){
      this.data.items[index].userChecked = false;
    } else{
      this.data.items[index].userChecked = true;
    }
    this.setData({items:this.data.items})
    let chekced = this.data.items.filter((item)=>{
      return item.userChecked == true;
    })
    console.log(chekced)
  },

  //清空选中的值
  getClear:function(){
    let checked = this.data.items;
    for (let i = 0; i < checked.length; i++){
      checked[i].userChecked = false;
    }
    this.setData({items:this.data.items})
  }
})

四、效果

#点击显示侧边栏按钮,从右边会划出侧边栏的模块,点击灰色区域方可隐藏侧边栏,其中也模拟了侧边栏要显示的内容、用户对其中出现的内容选取数据获取、一键清空功能。




猜你喜欢

转载自blog.csdn.net/WANG_CA/article/details/80789651