RockerSwitch.vue 2.27 KB
<script lang="ts" setup>
  const props = defineProps<{
    value?: boolean;
  }>();

  const emit = defineEmits(['update:value', 'change']);

  const handleChange = (event: Event) => {
    const _value = (event.target as HTMLInputElement).checked;
    emit('update:value', _value);
    emit('change', _value);
  };
</script>

<template>
  <label class="rocker-switch">
    <input :value="props.value" type="checkbox" :checked="props.value" @change="handleChange" />
    <span class="switch-left">ON</span>
    <span class="switch-right">OFF</span>
  </label>
</template>

<style scoped lang="less">
  .rocker-switch {
    display: flex;
    width: 72px;
    font-size: 14px;
    color: #fff;
    font-weight: 700;
    letter-spacing: 1px;
    border: 0.5em solid #eee;
    background-color: #999;
    user-select: none;

    input[type='checkbox'] {
      display: none;
    }

    input:checked + .switch-left + .switch-right {
      transform: rotate(-15deg) skew(-15deg) translate(-1px, -5px);
    }
    input:checked + .switch-left + .switch-right::before {
      background-color: #ccc;
      content: '';
      position: absolute;
      width: 3px;
      height: 30px;
      transform: skewY(75deg) skewX(4deg) rotate(5deg) translateX(1px);
      top: 1.5px;
      right: -1.5px;
    }

    input + .switch-left {
      transform: rotate(15deg) skew(17deg) translate(1px, -5px);
    }

    input:checked + .switch-left {
      background-color: #0084d0;
      transform: none;
    }

    input:not(:checked) + .switch-left {
      background-color: #ccc;
    }

    input:not(:checked) + .switch-left + .switch-right {
      background-color: #bd5757;
      color: #fff;
    }

    input + .switch-left::before {
      background-color: #ccc;
      content: '';
      position: absolute;
      width: 3px;
      height: 30px;
      background-color: #ccc;
      transform: skewY(-75deg) skewX(-4deg) rotate(-5deg) translateX(-1.5px);
      top: -1.5px;
      left: -1.5px;
    }

    .switch-left {
      width: 36px;
      height: 30px;
      text-align: center;
      line-height: 30px;
      cursor: pointer;
    }

    .switch-right {
      color: #888;
      width: 36px;
      height: 30px;
      text-align: center;
      line-height: 30px;
      background-color: #ddd;
      cursor: pointer;
    }
  }
</style>