<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>使用CSS實現折疊面板</title> <link rel="stylesheet" type="text/css" href="style.css"> </head> <body> <div class="container"> <input type="radio" id="item1" name="item"><label for="item1">Item1</label> <div class="context hiddenDiv"><span>span123span css html javascript jquery angularJS nodeJS css html javascript jquery angularJS nodeJS css html javascript jquery angularJS nodeJS</span></div> <input type="radio" id="item2" name="item"><label for="item2">Item2</label> <div class="context hiddenDiv"><span>hello world hello world hello world hello world hello world hello world hello world hello world hello world css html javascript jquery angularJS nodeJS css html javascript jquery angularJS nodeJS css html javascript jquery angularJS nodeJS css html javascript jquery angularJS nodeJS css html javascript jquery angularJS nodeJS</span></div> <input type="radio" id="item3" name="item"><label for="item3">Item3</label> <div class="context hiddenDiv"><span>hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world hello world </span></div> </div> </body> </html>
*{ margin:0; padding:0; } html,body{ width:100%; height:100%; } .container{ width:80%; height:400px; margin:0 auto; margin-top:30px; border:1px solid #dddddd; border-radius:1px; } input{ display:none; } label{ display:block; background-color: #F5F5F5; width:99%; height:40px; margin:0 auto; border:1px solid #dddddd; border-radius:2px; margin-top:5px; line-height: 40px; } .context{ width:99%; height:0px; margin:0 auto; border:1px solid #dddddd; border-radius:2px; visibility: hidden; transition:height 0.5s linear; -webkit-transition:height 0.5s linear; -moz-transition:height 0.5s linear; -ms-transition:height 0.5s linear; } input:checked + label + .context{ visibility: visible; height:150px; }
1、處理折疊和展開的動畫效果時候,使用transition(過渡效果),開始隱藏div時候使用了display:none; transition沒有效果,因為視圖中已經沒有div的物理位置,重新block后,回流和渲染,而visbility:hidden還保留其物理位置,只需要渲染就可以,transition起作用,記得以前做東西時候,經常會遇到相似的問題,但是,可能對display先入為主,總是先想到這個小玩意去隱藏元素,display會影響transition的效果,dom元素要在視圖中有位置,才能進行一系列動畫效果,注意這一點。
2、處理div時候用到了兄弟選擇器,經試驗,可以使用多個“+”選擇兄弟的兄弟等。