css+js 简单实现一个开关Switch效果【モモト】

<!DOCTYPE html>
<html lang="zh-cn">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Switch</title>
    <style>
      body {
        margin: 0;
        padding: 0;
      }
      #content {
        width: 100px;
        height: 50px;
        margin: 100px auto;
        padding: 5px;
        box-sizing: border-box;
        border-radius: 30px;
        background-color: gray;
        outline: greenyellow dotted thick;
        transition: background-color 0.3s;
      }
      #content::after{
        content: '';
        display: inline-block;
        width: 40px;
        height: 40px;
        background-color: #fff;
        border-radius: 20px;
        transition: all 0.3s;
      }
      #content.active{
        background-color: hotpink;
      }
      #content.active::after{
        transform: translateX(50px);
      }
      #content:active::after{
        width: 60px;
      }
      #content.active:active::after{
        transform: translateX(30px);
        width: 60px;
      }
    </style>
  </head>
  <body>
    <div id="content" onclick="toggle()">
    </div>
    <script>
      function toggle() {
        var content = document.querySelector("#content");
        if(content.className.includes('active')){
          content.className = content.className.replace('active', '');
        }else{
          content.classList.add('active');
        }
      }
    </script>
  </body>
</html>

上一篇:AOP


下一篇:最全知乎专栏合集:编程、python、爬虫、数据分析、挖掘、ML、NLP、DL...