微信小程序,自定义switch组件

在我看来这个主要是样式,相当于自己重新写一个switch样式,下面直接看源码

目录结构

switch.wxml

<view class="switch">
  <view class="container">
    <text class="title">自定义switch</text>
    <view class="switch-container">
      <view style="margin-right:20px" wx:for="{{switchData}}" wx:key="index">
        <switchItme id="{{item.id}}" bindmyevent="tagSwitch" dataItem="{{item}}">
        </switchItme>
      </view>
    </view>

    <text class="title">微信switch</text>
    <view class="switch-container">
      <switch/>
    </view>
  </view>
</view>

switch.js

Page({

  data: {
    switchData: [{
        id: 1,
        color: 'darkorange',
        isOn: false
      },
      {
        id: 2,
        color: 'red',
        isOn: true
      },
      {
        id: 3,
        isOn: false,
      },
      {
        id: 4,
        color: 'firebrick',
        isOn: true
      }
    ],

  },
  tagSwitch(event) {
    let index = event.currentTarget.id - 1;
    this.data.switchData[index].isOn = !this.data.switchData[index].isOn
    this.setData({
      switchData: this.data.switchData
    });
  }

})

switch.wxss

.switch-container {
  text-align: center;
  display: flex;
  display: -webkit-flex;
  margin-bottom: 200rpx;
}

switch.json

{
  "usingComponents": {
    "switchItme": "/component/switchItem/index"
  }
}

switchItem.wxml

<view class="switchBox">
  <view class="switch {{dataItem.isOn ? 'toggle-on' : 'toggle-off'}}" style="background-color:{{dataItem.isOn ? dataItem.color || '#09bb07' : '#ddd'}}" bindtap="tapSwitch">
  </view>
</view>

switchItem.js


Component({
  properties: {
    dataItem:{
      type:Object
    }
  },

  /**
   * 组件的初始数据
   */
  data: {

  },

  /**
   * 组件的方法列表
   */
  methods: {
    tapSwitch() {
      this.triggerEvent('myevent',{})
    }
  }
})

switchItem.wxss

.switch {
  position: relative;
  overflow: hidden;
  width: 52px;
  height: 32px;
  border-radius: 16px;
}

.switch::before {
  content: "";
  position: absolute;
  background-color: #fff;
  border-radius: 15px;
  transition: all ease-out 0.3s;
  -webkit-transition: all 0.3s;
}

.switch::after {
  position: absolute;
  display: inline-block;
  content: "";
  margin-top: 1px;
  height: 30px;
  width: 30px;
  border-radius: 50%;
  background-color: #fff;
  transition: left 0.2s ease-out;
  -webkit-transition: left ease-out 0.2s;
}

.toggle-off {
  background-color: #e5e5e5;
}

.toggle-off::before {
  width: 50px;
  height: 30px;
  left: 1px;
  top: 1px;
}

.toggle-off::after {
  left: 1px;
  box-shadow: 1px 2px 4px #aaa;
}

.toggle-on::before {
  width: 0px;
  height: 0px;
  left: 30px;
  top: 15px;
}

.toggle-on:after {
  left: 21px;
}

这个主要还是样式,把样式写出来了,就好办了,这里就不多讲了

猜你喜欢

转载自blog.csdn.net/dwb123456123456/article/details/85328093