jQuery之toggleClass解析
toggleClass(classname[,boolean]),其中第二个参数是可选的。当只传递一个参数时,toggleClass的原理如下:首先判断选择器是否有classname,如果有则动用removeClass(classname);否则动用addClass。当传递第二个参数(true)时,相当于调用addClass(classname);第二个参数传递(false)时,相当于调用removeClass(classname)。
<html> <head> <script type="text/javascript" src="/jquery/jquery.js"></script> <script type="text/javascript"> $(document).ready(function(){ demo1 $("button").click(function(){ $("p").toggleClass("main"); alert($("p").hasClass("main")); }); demo2 $("button").click(function(){ var $p = $("p"); var is_main_class = $p.hasClass("main"); if(is_main_class == true){ $p.removeClass("main"); }else{ $p.addClass("main"); } }); demo3 $("button").click(function(){ $("p").toggleClass("main"); }); }); </script> <style type="text/css"> .main { font-size:120%; color:red; } </style> </head> <body> <h1 id="h1">This is a heading</h1> <p class="main">This is a paragraph.</p> <p>This is another paragraph.</p> <button class="btn1">切换段落的 "main" 类</button> </body> </html>
相关推荐
EdwardSiCong 2020-11-23
85477104 2020-11-17
hhanbj 2020-11-17
81427005 2020-11-11
seoppt 2020-09-13
honeyth 2020-09-13
WRITEFORSHARE 2020-09-13
84483065 2020-09-11
momode 2020-09-11
85477104 2020-08-15
83510998 2020-08-08
82550495 2020-08-03
tthappyer 2020-08-03
84901334 2020-07-28
tthappyer 2020-07-25
TONIYH 2020-07-22
tztzyzyz 2020-07-20
83510998 2020-07-18
81463166 2020-07-17