2012年5月4日 星期五

用 jquery 實做 更多/減少 文字

本文主要參考jQuery More/Less Text一文。 首先,請在html中增加下列 elements
 <div class=\"more-less\">
   <div class=\"more-block\" ></div>
   <a href=\"#\" class=\"adjust\"></a>
 </div>
接著是 js:
  $(function(){                                                                   
                                                                                
// The height of the content block when it's not expanded                       
var adjustheight = 52;                                                          
// The "more" link text                                                         
var moreText = "+  More";                                                       
// The "less" link text                                                         
var lessText = "- Less";                                                        
                                                                                
// Sets the .more-block div to the specified height and hides any content that overflows
$(".more-less .more-block").css('height', adjustheight).css('overflow', 'hidden');
                                                                                
// The section added to the bottom of the "more-less" div                       
//$(".more-less").append("[...]");                                              
// Set the "More" text                                                          
$("a.adjust").text(moreText);                                                   
                                                                                
$(".adjust").toggle(function() {                                                
        $(this).parents("div:first").find(".more-block").css('height', 'auto').css('overflow', 'visible');
        // Hide the [...] when expanded                                         
        //$(this).parents("div:first").find("p.continued").css('display', 'none');
        $(this).text(lessText);                                                 
    }, function() {                                                             
        $(this).parents("div:first").find(".more-block").css('height', adjustheight).css('overflow', 'hidden');
        //$(this).parents("div:first").find("p.continued").css('display', 'block');
        $(this).text(moreText);                                                 
});                                                                             
});       
其中14,21,25是原文中用來增加 [...] 字串的。 我自己覺得不需要,所以註解掉了。