css实现开关样式

html部分,用ul和三个li元素实现开关:

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 
 4 <head>
 5     <meta charset="UTF-8">
 6     <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, user-scalable=no">
 7     <meta name="apple-mobile-web-app-capable" content="yes">
 8     <meta name="renderer" content="webkit|ie-comp|ie-stand">
 9     <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7; IE=EmulateIE9">
10     <!-- Page title -->
11     <title>开关</title>
12 </head>
13 
14 <body>
15     <ul>
16         <li class="normal_li"></li>
17         <li class="normal_li">关</li>
18         <li class="on_off on_off_ios"></li>
19     </ul>
20 </body>
21 
22 </html>

css样式部分:主要用到了transition属性

 1 * {
 2         margin: 0;
 3         padding: 0;
 4     }
 5     
 6     .on_off {
 7         background-color: #fff!important;
 8         background: url(img/stop.svg)no-repeat center;
 9         background-size: 10px 10px;
10         transition: all 0.5s;
11         -webkit-transition: all 0.5s;
12         -moz-transition: all 0.5s;
13         -o-transition: all 0.5s;
14         height: 24px;
15         width: 35px;
16         border-radius: 5px;
17         line-height: 30px;
18         text-align: center;
19         cursor: pointer;
20         top: 3px;
21         position: absolute;
22     }
23     
24     .on_off_open {
25        right: 5px;
26     }
27     
28     .on_off_close {
29         right: 40px;
30     }
31     
32     .normal_li {
33         height: 30px;
34         width: 40px;
35         float: left;
36         border-radius: 5px;
37         line-height: 30px;
38         text-align: center;
39         cursor: pointer;
40         background: skyblue;
41         color: #fff;
42     }
43     
44     ul {
45         height: 30px;
46         width: 80px;
47         border-radius: 5px;
48         background: skyblue;
49         margin-top: 20px;
50         margin-left: 20px;
51         list-style: none;
52         float: left;
53         cursor: pointer;
54         position: relative;
55         font-size: 14px;
56     }

js代码:ul的click事件控制开关的状态

 1 window.onload = function() {
 2             var ul = document.getElementsByTagName('ul')[0];
 3             var on_off = document.getElementsByClassName('on_off')[0];
 4             ul.onclick = function() {
 5                 var bool = on_off.getAttribute('class').indexOf('on_off_open');
 6                 if(bool!=-1) {
 7                     on_off.setAttribute('class',"on_off on_off_close");
 8                 }else{
 9                     on_off.setAttribute('class',"on_off on_off_open");
10                 }
11             }
12         }

 

posted @ 2017-04-10 16:45  雨停了  阅读(2611)  评论(0编辑  收藏  举报