日常开发中实现开关,或者更准确说实现单击按钮效果的方法很多,问题是怎么做才能让其更美观的展示在浏览器上。

  效果图如下:

        前端实现开关效果_html

  之前在网上看过不少实现的方法,其中就有一个是使用纯css3写出来的,以下是纯css代码实现的网站地址:https://proto.io/freebies/onoff/

  以下是该网站上展示的的源码:



<html>
<head>
<title>滑动开关</title>
<style type="text/css">
      /*div框样式*/
.onoffswitch {
position: relative;
width: 110px;
-webkit-user-select:none;
-moz-user-select:none;
-ms-user-select: none;
}
    /*将复选框隐藏*/
  .onoffswitch-checkbox {
    display: none;
}
      /*定义一个label标签*/
.onoffswitch-label {
display: block;
overflow: hidden;
cursor: pointer;
border: 2px solid #E3E3E3;
border-radius: 36px;
}
      /*定义一个span标签宽度为label的两倍先显示最左侧的一半*/
.onoffswitch-inner {
display: block;
width: 200%;
margin-left: -100%;
transition: margin 0.3s ease-in 0s;
}
      /*在span的前面和后面添加伪元素指定样式*/
.onoffswitch-inner:before, .onoffswitch-inner:after {
display: block;
float: left;
width: 50%;
height: 36px;
padding: 0;
line-height: 36px;
font-size: 16px;
color: white;
font-family: Trebuchet, Arial, sans-serif;
font-weight: bold;
box-sizing: border-box;
}
      /*在span前面添加的伪元素的中指定内容和样式*/
.onoffswitch-inner:before {
content: "on";
padding-left: 10px;
background-color: #FFFFFF;
color: #27A1CA;
text-align: left;
}
      /*在span的后面添加的伪元素中的指定内容和样式*/
.onoffswitch-inner:after {
content: "off";
padding-right: 10px;
background-color: #FFFFFF;
color: #666666;
text-align: right;
}
      /*小圆点的span标签*/
.onoffswitch-switch {
display: block;
width: 36px;
margin: 0px;
background: #A1A1A1;
position: absolute;
top: 0; bottom: 0;
right: 70px;
border: 2px solid #E3E3E3;
border-radius: 36px;
transition: all 0.3s ease-in 0s;
}
/*当是选中状态的时候label和span标签都是距离左边为0px*/
.onoffswitch-checkbox:checked + .onoffswitch-label .onoffswitch-inner {
margin-left: 0;
}
    /*当选中状态的时候label和圆点的span标签*/
.onoffswitch-checkbox:checked + .onoffswitch-label .onoffswitch-switch {
right: 0px;
background-color: #27A1CA;
}
</style>
</head>
<body>
<div class="onoffswitch">
<!-- 开关默认关闭 -->
<input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch">
<label class="onoffswitch-label" for="myonoffswitch">
<span class="onoffswitch-inner"></span>
<span class="onoffswitch-switch"></span>
</label>
</div>
</body>
</html>