1. 程式人生 > 實用技巧 >簡單的樹形選單如何寫?

簡單的樹形選單如何寫?

業務需求

資料結構中含有圖片、名稱、children的樹形結構,需要展示出每一級的圖片名稱和圖片,找了些樹形圖的外掛,都沒有展示大的圖片的,一般都是小圖示,就自己試著寫一個包含圖的簡單的外掛。

樹形圖的結構

<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結構採用遞迴的方式。

事件互動

初始狀態是全部展開,點選展開的圖示(-)會隱藏同級的UL元素,並改變圖示為(+)

$("#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的資料結構

   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)

完整的程式碼

    <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>

佛山vi設計https://www.houdianzi.com/fsvi/ 豌豆資源搜尋大全https://55wd.com

    <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 = '<ulhljs-string">'">';
        //設定迴圈,遍歷陣列中的每一項,最長不超過陣列的長度,依次遍歷
        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><span></span><a><img src="' + arr[i].img + '" alt=""/><div>' + arr[i].title + '</div></a>';
                } else {
                    html += '<li><span></span><a><div>' + arr[i].title + '</div></a>';
                }
            } else {
                if (arr[i].img) {
                    html += '<li><span></span><a><img src="' + arr[i].img + '" alt=""/><div>' + arr[i].title + '</div></a>';
                    html += render(arr[i].children, "item-group-innerpic")
                } else {
                    html += '<li><span></span><a><div>' + 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>