CSS Transition实现switch开关效果

知识点:

1.css3 transition的使用
2.label 和 checkbox的绑定
3.absolute与relative的使用
4.css3伪元素

讲解:

1.css3 transition
参考资料:http://www.w3school.com.cn/cssref/pr_transition.asp
个人理解:主要用于实现html元素的属性进行渐进式的变化。所以必输元素有三:属性 渐变时间长度 渐变效果

2.label和checkbox的绑定
参考资料:http://www.w3school.com.cn/tags/att_label_for.asp
个人理解:分为隐式和显示两种。通过id进行绑定,将label绑定到checkbox,能够让点击label时,让checkbox也获得焦点。

3.absolute和relateive的使用
参考资料:http://www.jianshu.com/p/a3da5e27d22b http://www.jianshu.com/p/07eb19957991
个人理解:absolute让元素脱离文档流,并且父元素彻底无法感知加了absolute的元素。relative给absolute添加了天花板,在relative的范围内变化。

设计思路:

开关按钮存在开关两种状态,最适合模拟的元素为checkbox。checkbox比较丑,所以我们需要保留元素功能,隐藏元素,同时还能够获得和丢失checkbox的状态。因此,需要引入label,作为显示。label作为容器,内部添加两个span。一个是用来显示on/off,一个用来表示开关的小按钮。on/off作为文字进行滑动效果,小按钮也引入滑动效果。

代码实现:
<html>
<head>
<title>switch</title>
<style type="text/css">
.switch{
display: block;
float: left;
position: relative;
width: 200px;
height: 50px;
}
#test{
display: none;
}
.switch-label{
display: block;
overflow: hidden;
width: 160px;
height: 50px;
border-radius: 8px;
border: 1px solid gray;
}
.switch-txt {
display: block;
width: 200%;
border-radius: 8px;
height: 50px;
transition:margin 0.3s ease-in;
}
.switch-txt::before,.switch-txt:after {
display: block;
float: right;
text-align: center;
line-height: 50px;
width: 50%;
height: 50px;
}
.switch-txt::before {
content: attr(data-on);
background-color: green;
}
.switch-txt::after {
content: attr(data-off);
background-color: gray;
}
.switch-switch {
display: block;
position: absolute;
width: 20px;
border-radius: 8px;
top: 0;
bottom: 0;
right: 89%;
background-color: white;
transition: all 0.3s ease-in;
}
#test:checked + .switch-label .switch-switch {
right:40px;
}
#test:checked + .switch-label .switch-txt {
margin-left: -100%;
}
</style>
</head>
<body>
<div class="switch">
<input id="test" type="checkbox">
<label for="test" class="switch-label">
<span class="switch-txt" data-on="ON" data-off="OFF"></span>
<span class="switch-switch"></span>
</label>
</div>
</body>
</html>

实现效果:

Paste_Image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 各种纯css图标 CSS3可以实现很多漂亮的图形,我收集了32种图形,在下面列出。直接用CSS3画出这些图形,要比...
    剑残阅读 9,775评论 0 8
  • 问答题47 /72 常见浏览器兼容性问题与解决方案? 参考答案 (1)浏览器兼容问题一:不同浏览器的标签默认的外补...
    _Yfling阅读 13,868评论 1 92
  • 1、垂直对齐 如果你用CSS,则你会有困惑:我该怎么垂直对齐容器中的元素?现在,利用CSS3的Transform,...
    kiddings阅读 3,231评论 0 11
  • 本课来自http://www.imooc.com/learn/9请不要用作商业用途。 HTML5 HTML介绍 H...
    PYLON阅读 3,359评论 0 5
  • 从大学毕业到现在,一直觉得自己的大学生活过得无怨无悔,没有什么遗憾,社团能做的也做了、恋爱能谈的也谈了、勤工俭学(...
    NJ_LIFE阅读 684评论 7 17