簡單的樹形菜單如何寫

查看樹形菜單

業務需求

數據結構中含有圖片、名稱、children的樹形結構,須要展現出每一級的圖片名稱和圖片,找了些樹形圖的插件,都沒有展現大的圖片的,通常都是小圖標,就本身試着寫一個包含圖的簡單的插件。javascript

樹形圖的結構

<ul>
    <li class="tree-item">
        <span class="icon glyphicon glyphicon-list-alt"></span>
        <a>
            <div class="item-name">name1</div>
        </a>
        <ul>
            <li class="tree-item">
                <span class="icon glyphicon glyphicon-list-alt"></span>
                <a>
                    <div class="item-name">name2</div>
                </a>
            </li>
        </ul>
    </li>
</ul>

主要是用ul和li展現,豎線是用ul的before僞元素寫的樣式,短橫線是li的before僞元素寫的樣式,要解決的問題是豎線和橫線的位置,LI中含有圖片和不含有圖片LI的class不一樣,同時li內部的ul的class 也不一樣,由於含有圖片和不含圖片設置的樣式不同。整個HTML結構採用遞歸的方式。css

事件交互

初始狀態是所有展開,點擊展開的圖標(-)會隱藏同級的UL元素,並改變圖標爲(+)html

$("#tree-box").on("click", ".icon", function() {
    $(this).siblings("ul").toggle();
    if ($(this).hasClass("glyphicon-minus")) {
        $(this).removeClass("glyphicon-minus").addClass("glyphicon-plus")
    } else if ($(this).hasClass("glyphicon-plus")) {
        $(this).removeClass("glyphicon-plus").addClass("glyphicon-minus")
    }
})

若是數據結構是含有PID的,須要先轉換成children的數據結構java

var json = [
       { id: 1, pid: 0, text: '1(XX公司)' },
       { id: 2, pid: 4, text: '2.1.1(開發部a-1組)' },
       { id: 3, pid: 0, text: '2(開發部)' },
       { id: 4, pid: 3, text: '2.1(開發部a)' },
       { id: 5, pid: 0, text: '3(人事部)' },
       { id: 6, pid: 5, text: '3.1(人事部A)' },
       { id: 7, pid: 0, text: '4(設計部)' },
       { id: 8, pid: 7, text: '4.1(設計部A)' },
       { id: 9, pid: 4, text: '2.1.2(開發部a-2組)' },
       { id: 11, pid: 2, text: '2.1.1.1(開發部a-1組>1小組)' },
       { id: 12, pid: 2, text: '2.1.1.2(開發部a-1組>2小組)' },
       { id: 13, pid: 5, text: '3.2(人事部A)' },
       { id: 19, pid: 5, text: '3.3(人事部B)' }
   ];

   function translateData(data, idStr, pidStr, chindrenStr) {
       var result = [],
           temp = {},
           id = idStr,
           pid = pidStr,
           children = chindrenStr,
           i = 0,
           j = 0,
           len = data.length;
       // 從新把數組中的對象從新放到一個新的對象中,新的對象是以id 的值爲鍵
       for (; i < len; i++) {
           // 創建temp對象,因爲對象是引用類型,修改temp或者data都會引發另外一方改變
           temp[data[i][id]] = data[i];
           // temp[a[i][id]] = JSON.parse(JSON.stringify(data[i])); 這種狀況data和temp是獨立的
       }
       // aVal 存儲數組中的對象,獲取新對象中key爲pid 的對象,若是存在	
       for (; j < len; j++) {
           var dataVal = data[j],
               tempObj = temp[dataVal[pid]];

           if (tempObj) {
               // 若是	tempObj[children]不存在,把tempObj[children]設爲數組	
               !tempObj[children] && (tempObj[children] = []);
               tempObj[children].push(dataVal);
           } else {
               // 若是不存在就把dataVal放到結果中		
               result.push(dataVal);
           }
       }
       console.log(data)
       return result;
   }

   document.getElementById("content").innerHTML = JSON.stringify(translateData(json, 'id', 'pid', 'chindren'), null, 2)

完整的代碼json

<style type="text/css">
    * {
        padding: 0;
        margin: 0;
    }

    #box {
        margin: 20px;
    }

    .item-group {
        list-style: none;
        margin-left: 20px;
        position: relative;
    }

    .item-group:before {
        content: "";
        display: inline-block;
        position: absolute;
        top: -10px;
        bottom: 15px;
        left: 0;
        border-left: 1px solid #67b2dd;
        z-index: 10;
    }

    .item-group-innerpic {
        list-style: none;
        margin-left: 20px;
        position: relative;
    }

    .item-group-innerpic:before {
        content: "";
        display: inline-block;
        position: absolute;
        top: -48px;
        bottom: 15px;
        left: 0;
        border-left: 1px solid #67b2dd;
        z-index: 10;
    }

    .tree-item {
        position: relative;
        line-height: 30px;
    }

    .tree-item:before {
        display: inline-block;
        content: "";
        position: absolute;
        top: 14px;
        width: 18px;
        height: 0;
        border-top: 1px dotted #67b2dd;
    }

    .tree-item1 {
        position: relative;
        line-height: 30px;
    }

    .tree-item1:before {
        display: inline-block;
        content: "";
        position: absolute;
        top: 48px;
        width: 18px;
        height: 0;
        border-top: 1px dotted #67b2dd;
    }

    .item-group li span {
        margin-left: 20px;
        color: #0994ce;
        margin-right: -15px;
    }

    .item-group li a {
        margin-left: 20px;
		display:inline-block;
    }

    .item-group li img {
	    width:100px;
        height: 100px;
		margin-right:10px;
    }

    .item-group li .item-name {
        display: inline-block
    }
    </style>
<div id="tree-box">
    </div>
    <script src="../js/jQuery-2.1.4.min.js"></script>
    <script>
    var data = [{
            title: 'biaoti1',
            img: '../imgs/green.png',
            children: [{
                    title: 'biaoti1-1',
                    img: '../imgs/1.jpg',
                    children: [{
                        title: 'biaoti1-1-1'
                    }, ]
                },
                {
                    title: 'biaoti1-2',
                    children: [{
                            title: 'biaoti1-2-1',
                            children: [{
                                    title: 'biaoti1-2-1-1'
                                },
                                {
                                    title: 'biaoti1-2-1-2',
                                    children: [{
                                            title: 'biaoti1-2-1-1-1'
                                        },
                                        {
                                            title: 'biaoti1-2-1-1-2'
                                        }
                                    ]
                                }
                            ]
                        },
                        {
                            title: 'biaoti1-2-2'
                        }
                    ]
                },
                {
                    title: 'biaoti1-3'
                }
            ]
        },
        {
            title: 'biaoti2',
            children: [{
                    title: 'biaoti2-1'
                },
                {
                    title: 'biaoti2-2'
                }
            ]
        },
        {
            title: 'biaoti3',
            children: [{
                    title: 'biaoti3-1'
                },
                {
                    title: 'biaoti3-2'
                }
            ]
        },
        {
            title: 'biaoti4'
        }
    ];
    var width = 50;
    var ulClass = "item-group"
    //封裝函數,方便調用
    function render(arr, ulClass) {
        //設置HTML爲ul標籤對的前半部分,用以將如下內容包括在ul中
        var html = '<ul class="' + ulClass + '">';
        //設置循環,遍歷數組中的每一項,最長不超過數組的長度,依次遍歷
        for (var i = 0; i < arr.length; i++) {
            //設置第一級ul中的li結構  <li><span>每一個標題</span></li>
            // console.log(arr[i])
            //判斷數組arr【i】的下方是否還有結構

            if (!arr[i].children) {
                if (arr[i].img) {
                    html += '<li class="tree-item1"><span class="icon glyphicon glyphicon-list-alt"></span><a><img src="' + arr[i].img + '" alt="" class="pic"/><div class="item-name">' + arr[i].title + '</div></a>';
                } else {
                    html += '<li class="tree-item"><span class="icon glyphicon glyphicon-list-alt"></span><a><div class="item-name">' + arr[i].title + '</div></a>';
                }
            } else {
                if (arr[i].img) {
                    html += '<li class="tree-item1"><span class="icon glyphicon glyphicon-minus"></span><a><img src="' + arr[i].img + '" alt="" class="pic"/><div class="item-name">' + arr[i].title + '</div></a>';
                    html += render(arr[i].children, "item-group-innerpic")
                } else {
                    html += '<li class="tree-item"><span class="icon glyphicon glyphicon-minus"></span><a><div class="item-name">' + arr[i].title + '</div></a>';
                    html += render(arr[i].children, "item-group")
                }
                //若是有,就增長結構

            }
            //設置第一級li的後標籤
            html += '</li>'
        }
        //設置第一級ul的後標籤
        html += '</ul>'
        return html;
    }
    //調用函數,傳參數組data,將其賦值給第一級ul的父級結構box,生成動態菜單
	var treebox = document.getElementById("tree-box")
    treebox.innerHTML = render(data, ulClass);

    $("#tree-box").on("click", ".icon", function() {
        $(this).siblings("ul").toggle();
        if ($(this).hasClass("glyphicon-minus")) {
            $(this).removeClass("glyphicon-minus").addClass("glyphicon-plus")
        } else if ($(this).hasClass("glyphicon-plus")) {
            $(this).removeClass("glyphicon-plus").addClass("glyphicon-minus")
        }
        //console.log(this)
    })
    </script>
相關文章
相關標籤/搜索