前些天在实现一个网站的需求:1、展示一个分类里边的条目;2、默认显示前十条,并显示一个展开按钮,点击展开按钮,点击后下拉显示该分类下所有条目;3、展开后,按钮变为收起按钮,点击收起恢复为默认显示条目。
试图想用jquery的slideToggle()、animate()函数实现,发现行不通,处理不了剩余内容的展开收起。后来想到通过联系展开按钮的class与主题内容的id匹配,在按钮的click事件里通过修改css和jquery的animate()函数结合实现想要的效果,代码如下(这边显示一段文字,默认显示文字前面的一部分内容):
jquery部分:
$(".more-btn").click(function(){ if($("#"+this.parentNode.className).css("height")=="100px"){ $("#"+this.parentNode.className).css("height","auto"); this.value="收起"; } else{ $("#"+this.parentNode.className).animate({height:"100px"},"slow"); this.value="展开"; } });
css部分:
body { margin:0; padding:40px 40px; background:#fff; font:Arial, Helvetica, sans-serif; font-size:13px; line-height:180%; } .case{ width:240px; } .entry{ clear: both; line-height: 1.6em; width:223px; height:100px; overflow:hidden; line-height:18px; border-top:#ff9933 1px solid; border-left:#ff9933 1px solid; border-right:#ff9933 1px solid; padding-left:5px; } .more-btn{ padding:0; width:230px; border-left:#ff9933 1px solid; border-right:#ff9933 1px solid; height:27px; background:#f4dc92; font-size:14px; font-weight:bolder; color:#000; }
html代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>demo</title> </head> <body> <div class="case"> <div class="entry" id="entry-1"> 显示的内容在此。。。 </div><!--entry--> <div class="entry-1"><input type="button" class="more-btn" value="更多" /></div> </div> <!--case--> </body> </html>
demo:猛击此查看demo