乐趣区

toggleSwitch-开关

实现效果:

HTML:

<template>
  <label role="checkbox" :class="['switch', { toggled}]">
    <input type="checkbox" class="switch-input" @change="toggle" />
    <div class="switch-core" :style="{backgroundColor: toggled ? colorChecked : colorUnchecked}" >
      <div class="switch-button"
        :style="{transition: `transform ${speed}ms`,
          transform: toggled ? null : `translate3d(26px, 0px, 0px)`
        }"
      ></div>
    </div>
    <span class="switch-label label-right" v-if="toggled" v-html="labelChecked"> </span>
    <span class="switch-label label-left" v-html="labelUnchecked" v-else> </span>
  </label>
</template>

JS:

<script>
export default {
  name: "toggleSwitch",
  props: {value: { type: Boolean, default: true},
    speed: {type: Number, default: 100},
    present: {type: Object, default: {}},
    id: {default: ''},
    index: {default: ''},
    open: {type: String, default: '开'},
    close: {type: String, default: '关'},
    openBgColor: {type: String, default: '#409EFF'},
    closeBgcolor: {type: String, default: '#DCDFE6'}
  },
  data() {
    return {
      toggled: this.value,
      colorChecked: this.openBgColor,
      colorUnchecked: this.closeBgcolor,
      labelChecked: this.open,
      labelUnchecked: this.close
    };
  },
  methods: {toggle(event) {
      this.toggled = !this.toggled;
      this.$emit("change", {bool: this.toggled, index: this.present.$index, id: this.present.row.id});
    }
  },
  created() {}
};
</script>

CSS:

<style lang="scss" scoped>
.switch {
  display: inline-block;
  position: relative;
  overflow: hidden;
  vertical-align: middle;
  user-select: none;
  font-size: 10px;
  cursor: pointer;
  .switch-input {display: none;}
  .switch-label {
    position: absolute;
    top: 0;
    font-weight: 600;
    color: white;
    z-index: 2;
    &.label-left {
      left: 5px;
      line-height: 25px;
      border-radius: 100px;
    }
    &.label-right {
      right: 5px;
      line-height: 25px;
      border-radius: 100px;
    }
  }
  .switch-core {
    display: block;
    position: relative;
    box-sizing: border-box;
    outline: 0;
    margin: 0;
    transition: border-color 0.3s, background-color 0.3s;
    user-select: none;
    width: 50px;
    height: 25px;
    border-radius: 100px;
    line-height: 25px;
    .switch-button {
      width: 20px;
      height: 20px;
      display: block;
      position: absolute;
      overflow: hidden;
      top: 3px;
      left: 2px;
      z-index: 3;
      transform: translate3d(0, 0, 0);
      background-color: #fff;
      border-radius: 100px;
    }
  }
}
</style>





退出移动版