bootstrap-treeview 是bootstrap的一個樹形插件,插件依賴:
bootstrap/3.3.7
jquery/3.3.1
經過驗證,它不可以在 bootstrap 高於 3.3.7 版本中使用,當前 treeview 的版本為 bootstrap-treeview/1.2.0 , bootstrap/3.3.7
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdn.bootcss.com/bootstrap-treeview/1.2.0/bootstrap-treeview.min.js"></script>
其實它這個不兼容是因為這個插件用了 版本3 的圖標,而 bootstrap 4 卻把這些圖標給干掉了,因此需要手動添加這些圖標文件 Glyphicons.scss:
@charset 'utf-8'; at-root { // Import the fonts @font-face { font-family: 'Glyphicons Halflings'; src: url('../font/bootstrap/glyphicons-halflings-regular.eot'); src: url('../font/bootstrap/glyphicons-halflings-regular.eot') format('embedded-opentype'), url('../font/bootstrap/glyphicons-halflings-regular.ttf') format('truetype'), url('../font/bootstrap/glyphicons-halflings-regular.woff') format('woff'), url('../font/bootstrap/glyphicons-halflings-regular.woff2') format('woff2'), url('../font/bootstrap/glyphicons-halflings-regular.svg') format('svg'); font-weight: normal; font-style: normal; } } // Catchall baseclass .glyphicon { position: relative; top: 1px; display: inline-block; font-family: 'Glyphicons Halflings'; font-style: normal; font-weight: normal; line-height: 1; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; }
bootstrap 3 國內打不開不了,這是個英文版,需要翻牆:https://getbootstrap.com/docs/3.3/getting-started/ 去下載。
在html中,只寫一個存放的文件樹的容器即可:
<div id="tree"></div>
假定先做一個假數據,使用 tree.json:
[ { "text":"Bakersfield office", "nodes": [ { "text":"Bakersfield BD" }, { "text":"Bakersfield marketing" }, { "text":"Bakersfield HR" } ] }, { "text":"Stockton office", "nodes": [ { "text":"Stockton service" }, { "text":"Stockton After sales" }, { "text":"Stockton Field service" }, { "text":"Stockton Finance" }, { "text":"Stockton HR" } ] }, { "text":"Chesapeake office HR" } ]
然后使用 ajax 將數據填入 #tree 的容器中:
function getTree(){ var url = 'http://127.0.0.1:8020/localhost-cloudClocking-CMS/js/tree.json'; $.ajax({ type:"get", url:url, dataType: 'json', contentType: 'application/json; charset=utf-8', success: function(data) { console.log(data); $('#tree').treeview({ levels: 1, data:data, selectedBackColor: 'rgba(#000000,.12)' //這是我本地測試的顏色 可以略過 }); } }); }