情形:本類別下面有好多子類別,每個子類別下面又有好多孫類別;需求:當點擊本類別時,子類別如果是顯示的就讓它隱藏,子類別如果是隱藏的就讓它顯示。
效果如下:

圖(1)點擊前

圖(2)點擊后
代碼如下:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title></title> <style> *{ margin:0; padding:0; list-style: none; } .box{ width: 250px; height: auto; padding: 20px; background: lightgrey; margin:0 auto; } .box li{ line-height: 30px; /*注意:height沒有被設置,可以根據實際需要自動調整*/ position: relative; } .box li em{ position: absolute; left:0; top:7px; width: 16px; height: 16px; background-image: url("http://www.qdfuns.com/misc.php?mod=attach&genre=editor&aid=123b5048273b92eb544ad6eb0ed57c44"); background-size:100%; cursor: pointer; } .box li em.open{ background-image: url("http://www.qdfuns.com/misc.php?mod=attach&genre=editor&aid=8f89447399822b0294ae590ccc641bf5"); background-size:100%; } .box li span{ padding-left: 20px; /*因為span前面的em已經絕對定位,脫離文檔流了,所以span的左邊界直達 li*/ } .box ul{ display: none; } .two{ margin-left: 20px; } .three{ margin-left: 40px; } .four{ margin-left: 40px; } /*ul.box下的li顯示,其中有折疊的li加em; ul.box下的ul隱藏,其內部的li是沒法顯示的*/ </style></head><body><ul class="box"> <li><em></em><span>第一級第一個</span> <ul class="two"> <li><span>第二級第一個</span></li> <li><em></em><span>第二級第二個</span> <ul class="three"> <li><em></em><span>第三級第一個</span> <ul class="four"> <li><span>第四級第一個</span></li> <li><span>第四級第二個</span></li> </ul> </li> <li><span>第三級第二個</span></li> </ul> </li> <li><em></em><span>第二級第三個</span> <ul class="three"> <li><span>第三級第一個</span></li> <li><span>第三級第二個</span></li> </ul> </li> </ul> </li> <li><em></em><span>第一級第一個</span> <ul class="two"> <li><span>第二級第一個</span></li> <li><em></em><span>第二級第二個</span> <ul class="three"> <li><em></em><span>第三級第一個</span> <ul class="four"> <li><span>第四級第一個</span></li> <li><span>第四級第二個</span></li> </ul> </li> <li><span>第三級第二個</span></li> </ul> </li> </ul> </li></ul><script src="http://s0.kuaizhan.com/res/skin/js/lib/jquery-2.0.3.min.js"></script><script> /*思路: * 1.讓前面有em的span加上小手效果; * 2.點擊span or em的時候,看他父容器下是否有ul,如果有,讓其顯示,否則,隱藏 * */ var $box=$('.box'); var $aSpan=$box.find('span'); //1.讓前面有em的span加上小手效果; $aSpan.each(function(index,item){ //if($(item).prev().length){ $(item).css('cursor','pointer');};思路1: $(item).prev('em').next('span').css('cursor','pointer'); //思路2: }); //2.點擊span or em的時候,看他父容器下是否有ul,如果有,讓其顯示,否則,隱藏 $box.click(function(e){ //當點擊的事件源是em or span的時候,我們看其父級下是否有ul // 如果有:展開讓其閉合,閉合就讓其展開; if(e.target.tagName.toLowerCase()=='em' || e.target.tagName.toLowerCase()=='span'){ var $parent=$(e.target).parent(); var $ul=$parent.children('ul'); if($ul){ if($ul.css('display')=='block'){//展開,讓其閉合 //當閉合的時候,讓當前容器下,所有的em都移除open,所有的ul都隱藏; $parent.find('ul').hide(); $parent.find('em').removeClass('open'); }else{ //閉合讓其展開 $ul.show(); $parent.children('em').addClass('open'); } } } })</script></body></html>以上就是本文的全部內容,希望本文的內容對大家的學習或者工作能帶來一定的幫助,同時也希望多多支持武林網!
新聞熱點
疑難解答