作者:wtcsy | 數據源:數組混合 JSON 結構 | 對比基準:dhtree、梅花雪樹
var data = [
{id: 1, text: '節點1', children: [
{id: 2, text: '子節點1'},
{id: 3, text: '子節點2', children: [...]}
]}
];
function buildTree(nodes, parentUl) {
var frag = document.createDocumentFragment();
nodes.forEach(function(node, index) {
var li = document.createElement('li');
var span = document.createElement('span');
span.className = 'tvdash-f' + (index === nodes.length-1 ? 'l' : '');
span.innerHTML = node.text;
li.appendChild(span);
if (node.children && node.children.length) {
var ul = document.createElement('ul');
ul.className = 'folder';
buildTree(node.children, ul);
li.appendChild(ul);
}
frag.appendChild(li);
});
parentUl.appendChild(frag);
}
/* CSS 關鍵類名 */
.tvdash-f { background-position: -240px -40px; } /* + 號 */
.tvdash-f-open { background-position: -200px -40px; } /* - 號 */
.tvdash-fl { background-position: -100px -40px; } /* 末節點 + */
.tvdash-fl-open{ background-position: -80px -40px; } /* 末節點 - */
.tvicon-open { background-position: -160px -40px; } /* 文件夾打開 */
.tvdash-t { background-position: -180px -40px; } /* 中間節點竪線 */
.tvdash-tl { background-position: -60px -40px; } /* 末節點竪線 */
<div id="demo"></div>
<script>
// 工具函數:瀏覽器檢測、DOM 操作、事件綁定、樣式設置、extend、each 等
// 核心 Tree 類實現
</script>
// 瀏覽器檢測與 IE6 背景緩存
window.Sys = function(ua){ ... };
window.Sys.ie6 && doc.execCommand("BackgroundImageCache", false, true);
// 通用 DOM 創建
window.$c = function(name, parent) {
var elem = doc.createElement(name);
parent && parent.appendChild(elem);
return elem;
};
// 事件綁定(兼容 IE)
window.addListener = function(element, e, fn) { ... };
// 樣式設置
window.setStyle = function(e, o) {
if (typeof o == "string") e.style.cssText = o;
else for (var i in o) e.style[i] = o[i];
};
// jQuery 風格 extend
window.extend = function() { ... };
// 遍歷工具
window.each = function(object, callback, args) { ... };
EasyTree 以 64 行核心代碼實現了功能完整、性能優異的樹形組件。關鍵在於:JSON 數據驅動 + DocumentFragment 離線構建 + CSS Sprite 圖標 + 事件委託 四大支柱。代碼結構清晰,易於擴展檢查框、拖拽、搜索等高級功能,是中小型項目樹形組件的優秀選型參考。