HTML 开关按钮

  • 代码
<!-- 开关按钮 -->
<p class="btn-on" onclick="on_off()">
  <!-- 圆点 -->
  <span class="btn-on-circle"></span>
  <!-- 文字 -->
  <span class="btn-on-text">ON</span>
</p>
<script>
  function on_off(type){
    var btn = document.getElementsByClassName("btn-on")[0];
    var circle = document.getElementsByClassName("btn-on-circle")[0];
    var text = document.getElementsByClassName("btn-on-text")[0];

    if(!type){
      btn.style= "background-color: #ccc;"
      circle.style="left: 40px;background-color: #888;box-shadow: 0 0 10px #888;";
      text.style="right: 30px;color: #888;";
      text.innerText="OFF";
    } else {
      btn.style= ""
      circle.style="";
      text.style="";
      text.innerText="ON";
    }
    btn.setAttribute("onclick", "on_off(" + !type + ")"); // 修改状态
  }
  on_off(false)// 关闭按钮
</script>
<style>
  /* 开关按钮 */
  .btn-on{
    width: 60px;
    height: 25px;
    margin: 0 3px;
    border-radius: 25px;
    font-size: 14px;
  }
  .btn-on{
    cursor: pointer;
    position: relative;
    border: 1px solid white;
    background-color: #12B090;
  }
  .btn-on-circle{
    position: absolute;
    width: 15px;
    height: 15px;
    top: 5px;
    left: 5px;
    background-color: rgb(255, 255, 255);
    border-radius: 50%;
    box-shadow: 0 0 10px white;
    transition: all .5s;
  }
  .btn-on-text{
    position: absolute;
    right: 10px;
    line-height: 25px;
    color: white;
    transition: all .5s;
  }
</style>
  • 效果
  • 执行效果

版权声明:本文为weixin_52707625原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。