开关是同一个事物控制两种不同的状态,开关是唯一的,但是内容是改变的 例如:开和关的切换,本来为开的状态,点击切换为关的状态,开关随意切换。
<!doctype html> <html> <head> <meta charset="utf-8"> <title>jquery实现开关按钮</title> <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script> <style> .div1{ width: 60px; height: 26px; border-radius: 15px; overflow: hidden; position: relative; } .div1 .left{ position: absolute; left:4px; } .div1 .right{ position: absolute; right:4px; } .div2{ width: 30px; height: 20px; border-radius: 9px; background: #fff; position: absolute; } .open1{ background: #ddd; } .open2{ top: 3px; left: 5px; } .close1{ width: 60px; height: 26px; border-radius: 15px; overflow: hidden; position: relative; background: #659dea; } .close2{ left: 25px; top: 3px; } </style> </head> <body> <div class="div1 open1"> <span class="left"></span> <span class="right"></span> <div class="div2 open2"></div> </div> <script> $(function(){ $(".div2").on('click',function() { // console.log('className======='+$(this).parent().get(0).className) $(this).parent().toggleClass('close1'); $(this).parent().toggleClass('open1'); $(this).toggleClass('close2'); $(this).toggleClass('open2'); }) }); </script> </body> </html>