2012-06-03 65 views

回答

0

基本上有2種方法。

  1. 使用仄切換類和使用CSS來定義什麼隱藏

    /* show only the first 3 list items */ 
    ul.collapsed li:nth-child(n+4) { 
        display: none; 
    } 
    
    var $list = $(ul.collapsed); // initially the list is collapsed 
    
    // use a show-more link to toggle display of remaining items 
    $("a.show-more").click(function(){ 
    
        // get the current state of the list by querying the className 
        var shouldShow = $list.hasClass("collapsed") == true; 
        $list.toggleClass("collapsed"); 
    
        // set the link text according to the task (show or hide) 
        $(this).html(shouldShow ? "Show less" : "Show more"); 
    
        // its a link, don't follow it 
        return false; 
    }); 
    
  2. 使用仄 「獨立」

    var $list = $(ul); 
    
    // use the link to set the css properties directly 
    $("a.show-more").click(function(){ 
    
        var shouldShow = $list.hasClass("collapsed") == true; 
    
        $("li:nth-child(n+4)", $list).css({ 
         "display": shouldShow : "" : "none" 
        }); 
    
        $(this).html(shouldShow ? "Show less" : "Show more"); 
        return false; 
    }); 
    
1

這裏的一種方法來完成你所要求的。

$(function() { 
    $('li').slice(5).toggle(); 

    $('span').click(function() { 
    $('li').slice(5).toggle(); 
    }); 
});​ 

第一.slice(5).toggle()函數採用選擇的所有列表中的項目,縮小範圍到元素的子集,通過端部開始於索引5。然後它切換它在該子集中找到的第一個元素的可見狀態。

然後,我們將一個函數附加到span上的click事件,這是我們的Show/Hide元素。該功能實際上與我們爲了隱藏索引5之後的所有元素而運行的初始功能相同。

查看此JS Fiddle作爲一個工作示例。另外,這裏進一步參考的是the docs on .slice(),這裏是the docs on .toggle()

希望有幫助!