让我们使用 HTML 和 CSS 创建一个自定义切换开关。
步骤 1-HTML。
第 2 步 - 基本样式
步骤 3——创建切换按钮并隐藏复选框。
步骤 4-添加功能。
大家好!在本快速教程中,我们将学习如何使用 HTML 和 CSS 创建自定义切换开关。
步骤 1-HTML。
<label class="switch">
     <input type="checkbox" class="checkbox">
     <span class="toggle-thumb">
          <svg xmlns="http://www.w3.org/2000/svg" width="36" height="36" viewBox="0 0 24 24" style="fill:#4ADE80;transform:;-ms-filter:"><path d="M10 15.586L6.707 12.293 5.293 13.707 10 18.414 19.707 8.707 18.293 7.293z"></path></svg>
          <svg xmlns="http://www.w3.org/2000/svg" width="36" height="36" viewBox="0 0 24 24" style="fill:#F87171;transform:;-ms-filter:"><path d="M16.192 6.344L11.949 10.586 7.707 6.344 6.293 7.758 10.535 12 6.293 16.242 7.707 17.656 11.949 13.414 16.192 17.656 17.606 16.242 13.364 12 17.606 7.758z"></path></svg>
     </span>
</label>
这里,带有“switch”类的标签就像我们开关的主容器。带有“toggle-thumb”类的 span 是开关的圆形部分,span 内部是我们将要使用的两个 SVG 图标。我们将使用复选框来切换开关。
第 2 步 - 基本样式
.switch {
      display: inline-block;
      width: 60px;
      height: 34px;
      position: relative;
    }
.toggle-thumb {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      display: flex;
      justify-content: space-between;
      align-items: center;
      background-color: #475569;
      border-radius: 40px;
      cursor: pointer;
    }
完成这些样式后,开关应该看起来像这样
步骤 3——创建切换按钮并隐藏复选框。
为了创建切换拇指,我们需要将“::before”伪元素添加到“toggle-thumb”。
 .toggle-thumb:before {
      content: "";
      height: 26px;
      width: 26px;
      position: absolute;
      left: 4px;
      bottom: 4px;
      border-radius: 50%;
      background-color: #E2E8F0;
      transition: .4s all ease;
    }
并隐藏复选框
.checkbox {
      opacity: 0;
      width: 0;
      height: 0;
    }
步骤 4-添加功能。
为了给开关添加这个功能,我们需要在复选框被选中时,为 'toggle-thumb::before' 添加 transform。为此,
.checkbox:checked + .toggle-thumb:before {
      transform: translateX(26px);
    }
谢谢😀
文章来源:https://dev.to/devggaurav/let-s-create-a-custom-toggle-switch-using-html-and-css-33df 后端开发教程 - Java、Spring Boot 实战 - msg200.com
            后端开发教程 - Java、Spring Boot 实战 - msg200.com
          

