纯css实现点击事件
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>点击</title> 6 <style> 7 * { 8 margin: 0; 9 padding: 0; 10 } 11 12 .box { 13 position: relative; 14 display: block; 15 float: left; 16 width: 50px; 17 height: 50px; 18 margin-top: 100px; 19 margin-left: 100px; 20 border: 1px solid #18c250; 21 border-radius: 3px; 22 } 23 24 input[type=checkbox]:checked + label .box:before { 25 content: ""; 26 position: absolute; 27 top: 28px; 28 left: 2px; 29 width: 23px; 30 height: 3px; 31 background-color: #18c250; 32 transform: rotate(45deg); 33 -webkit-transform: rotate(45deg); 34 } 35 36 input[type=checkbox]:checked + label .box:after { 37 content: ""; 38 position: absolute; 39 top: 24px; 40 left: 15px; 41 width: 37px; 42 height: 3px; 43 background-color: #18c250; 44 transform: rotate(-45deg); 45 -webkit-transform: rotate(-45deg); 46 } 47 48 .info { 49 float: left; 50 margin-top: 92px; 51 margin-left: 10px; 52 font-size: 48px; 53 user-select: none; 54 } 55 56 label { 57 display: inline-block; 58 max-width: 100%; 59 } 60 61 input[type=checkbox]{ 62 display: none; 63 } 64 65 </style> 66 </head> 67 <body> 68 <input id="input" type="checkbox"> 69 <label for="input"> 70 <span class="box"></span> 71 <span class="info">已阅读协议书</span> 72 </label> 73 </body> 74 </html>
效果:
注意点:input要写在label前面,因为 + 选择器指的是兄弟元素中的弟弟元素,不包括哥哥元素。
写这个的初衷就在于那个亘古不变的道理,能用CSS解决的就不用js
在来个炫酷点的开关
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 <style> 7 *{ 8 margin: 0; 9 padding: 0; 10 } 11 body{ 12 background-color: #abcdef; 13 } 14 input{ 15 display: none; 16 } 17 .switch{ 18 position: relative; 19 display: block; 20 width: 38px; 21 height: 20px; 22 cursor: pointer; 23 user-select: none; 24 margin-top: 100px; 25 margin-left: 100px; 26 border-radius: 10px; 27 background-color: #b0b0b0; 28 } 29 .switch:before{ 30 content: 'OFF'; 31 position: absolute; 32 top: 1px; 33 right: 2px; 34 font-size: 12px; 35 color: #fff; 36 transform: scale(.75); 37 -webkit-transform: scale(.75); 38 } 39 .switch:after{ 40 content: ""; 41 position: absolute; 42 top: -1px; 43 left: -6px; 44 width: 22px; 45 height: 22px; 46 border-radius: 50%; 47 background-color: #fff; 48 -webkit-transition: left 200ms linear; 49 } 50 input[type=checkbox]:checked + label .switch{ 51 background-color: #18c250; 52 } 53 input[type=checkbox]:checked + label .switch:before{ 54 content: "ON"; 55 right: 15px; 56 } 57 input[type=checkbox]:checked + label .switch:after{ 58 left: 25px; 59 } 60 </style> 61 </head> 62 <body> 63 <input id="input1" type="checkbox"> 64 <label for="input1"> 65 <a class="switch"> 66 67 </a> 68 </label> 69 <input id="input2" type="checkbox"> 70 <label for="input2"> 71 <a class="switch"> 72 73 </a> 74 </label> 75 </body> 76 </html>
效果:
myGitgub https://github.com/mfx55
希望我的博客能帮到你