【CSS】css实现仿IOS的switch开关效果

使用纯css实现效果类似苹果手机开关的样式。

【CSS】css实现仿IOS的switch开关效果

By img Microanswer Create at:Sep 9, 2019, 6:04:17 PM 

Tags: switch inpupt css checkbox

使用纯css实现效果类似苹果手机开关的样式。


重要声明:本文章仅仅代表了作者个人对此观点的理解和表述。读者请查阅时持自己的意见进行讨论。

一、先看效果

二、再看代码

1、html布局代码

<!-- 使用 label 包裹里面的所有内容,这样点击 label 区域,就等于是点击 input 区域,即便隐藏了 input ,也依然有效。 -->
<label class="ios-switch">

    <!-- input 输入框是用于保持开关状态的。同时在实际使用时,input也可方便获取到当前的开关状态。 -->
    <input class="switch" type="checkbox"/>
    <!-- 但默认的 input 效果不是很好看,所以后面紧接着跟随一个空的 i 节点,所有效果都将通过 i 展示, -->
    <!-- 并且 i 和 input 之间不能有任何节点或文字。 -->
    <i></i>

</label>

2、css样式代码

/* 对开关整体样式设定 */
label.ios-switch {
    position: relative;
    display: inline-block;
    cursor: pointer;
    margin: 0;
    padding: 0;
}

/* 首先隐藏input输入框 */
label.ios-switch input[type="checkbox"] {
    display: none;
}

/* 确定switch开关的盒子模型的大小和边框效果,以及[关]的状态下背景颜色和边框颜色*/
label.ios-switch input[type="checkbox"]+i {
    display:          block;
    width:            108px;
    height:           50px;
    box-shadow:       0 0 3px black inset;
    border:           2px solid gray;       /* 边框颜色 */
    border-radius:    9999px;               /* 将圆角设置为一个较大的值,可以实现两边呈现半圆形的效果。 */
    background-color: #ffffff;              /* 背景颜色 */


    -webkit-transition-duration: 300ms;     /* 动画过度时长 */
    -moz-transition-duration:    300ms;
    -ms-transition-duration:     300ms;
    -o-transition-duration:      300ms;
    transition-duration:         300ms;
}

/* 确定[开]的状态下背景颜色和边框颜色 */
label.ios-switch input[type="checkbox"]:checked+i {
    background-color: rgba(0, 211, 0, 1);                 /* 背景颜色 */
}

/* 确定[关]状态下的指示圆块的样式,这些样式也会作用于开状态*/
label.ios-switch input[type="checkbox"]+i::before {
    content:            ' ';
    position:           absolute;
    width:              55px;           /* 圆块的宽度 */
    height:             46px;           /* 圆块的高度 */
    background-color:   #ededed;        /* 关闭时背景色 */
    box-shadow:         0 0 4px #000000;
    border-radius:      9999px;
    left:               2px;

    -webkit-transition: inherit;
    -moz-transition:    inherit;
    -ms-transition:     inherit;
    -o-transition:      inherit;
    transition:         inherit;
}

/* 确定[开]状态下的指示圆块的样式 */
label.ios-switch input[type="checkbox"]:checked+i::before {
    left: 50px;                                      /* 开启时划过的距离 */
    background-color: rgba(255, 255, 255, 1);        /* 背景颜色 */
}
Full text complete, Reproduction please indicate the source. Help you? Not as good as one:
Comment(Comments need to be logged in. You are not logged in.)
You need to log in before you can comment.

Comments (0 Comments)