Skip to content

如何实现一个平滑切换的toggle组件

  1. 首先编写HTML代码如下
html
<section class="toggle-box">
    <!-- for 与id让标签点击时选中checkbox -->
    <input type="checkbox" name="toggle" id="toggle"/>
    <label for="toggle"></label>
</section>
<section class="toggle-box">
    <!-- for 与id让标签点击时选中checkbox -->
    <input type="checkbox" name="toggle" id="toggle"/>
    <label for="toggle"></label>
</section>
  1. 编写样式文件
scss
.toggle-box {
  /* 隐藏input */
  input[type="checkbox"] {
    display: none;
  }

  /* 转换为可以设置宽高的行内样式 */
  label {
    width: 100px;
    height: 50px;
    display: inline-block;
    background: #777;
    border: 2px solid #555;
    border-radius: 30px;
    position: relative;
    transition: all 0.3s;
  }

  /* 伪元素内部画小球 */
  label::after {
    content: "";
    display: block;
    width: 42px;
    height: 42px;
    background: #555;
    position: absolute;
    border-radius: 50%;
    left: 4px;
    top: 4px;
    transition: all 0.3s;
  }

  /* 改变label背景和边框 */
  input[type="checkbox"]:checked ~ label {
    background-color: #00a0fc;
    border-color: #006dc9;
  }

  /* 改变小球位置颜色 */
  input[type="checkbox"]:checked ~ label::after {
    transform: translateX(50px);
    background-color: #0054b0;
  }
}
.toggle-box {
  /* 隐藏input */
  input[type="checkbox"] {
    display: none;
  }

  /* 转换为可以设置宽高的行内样式 */
  label {
    width: 100px;
    height: 50px;
    display: inline-block;
    background: #777;
    border: 2px solid #555;
    border-radius: 30px;
    position: relative;
    transition: all 0.3s;
  }

  /* 伪元素内部画小球 */
  label::after {
    content: "";
    display: block;
    width: 42px;
    height: 42px;
    background: #555;
    position: absolute;
    border-radius: 50%;
    left: 4px;
    top: 4px;
    transition: all 0.3s;
  }

  /* 改变label背景和边框 */
  input[type="checkbox"]:checked ~ label {
    background-color: #00a0fc;
    border-color: #006dc9;
  }

  /* 改变小球位置颜色 */
  input[type="checkbox"]:checked ~ label::after {
    transform: translateX(50px);
    background-color: #0054b0;
  }
}

最终的效果如下