树型菜单是我们在开发中经常用到的数据组合和显示方式, dTree(http://www.destroydrop.com/javascripts/tree/) dTree是一种免费的javascript树型菜单, 它支持ie5+, ns 6+, Opera 7+以及Mozilla浏览器 使用简单: 引入树, 在head中加入dtree.js和dtree.css(注意要把js,css和img放到相应目录), 如下所示: rel="StyleSheet" href="dtree.css" type="text/css" /> <script type="text/javascript" src="dtree.js"></script> 实例化树并显示
add方法的参数说明 id:当前节点标识, pid:父节点标识, name:当前节点名字, url:当菜单被点击时响应的超链接, title:提示语, target:在目标窗口打开链接, icon:关闭时的显示图标, iconOpen:打开时的显示图标, open:默认的打开状态, true打开, false关闭(不过它会读cookie, 所以有时看不出效果) dTree.prototype.add = function(id, pid, name, url, title, target, icon, iconOpen, open) Xtree(http://webfx.eae.net/dhtml/xtree/implementation.html) 相对dTree来说, xTree功能要多一些, 能动态增减树的节点 引入树:
<script src="xtree.js"></script> type="text/css" rel="stylesheet" href="xtree.css"> 实例化树, 并显示
<script> if (document.getElementById) { var tree = new WebFXTree('Root'); tree.setBehavior('classic'); var a = new WebFXTreeItem('1'); tree.add(a); var b = new WebFXTreeItem('1.1'); a.add(b); b.add(new WebFXTreeItem('1.1.1')); b.add(new WebFXTreeItem('1.1.2')); b.add(new WebFXTreeItem('1.1.3')); var f = new WebFXTreeItem('1.1.4'); b.add(f); f.add(new WebFXTreeItem('1.1.4.1')); f.add(new WebFXTreeItem('1.1.4.2')); f.add(new WebFXTreeItem('1.1.4.3')); var c = new WebFXTreeItem('1.2'); a.add(c); c.add(new WebFXTreeItem('1.5.1')); c.add(new WebFXTreeItem('1.5.2')); c.add(new WebFXTreeItem('1.5.3')); a.add(new WebFXTreeItem('1.3')); a.add(new WebFXTreeItem('1.4')); a.add(new WebFXTreeItem('1.5')); var d = new WebFXTreeItem('2'); tree.add(d); var e = new WebFXTreeItem('2.1'); d.add(e); e.add(new WebFXTreeItem('2.1.1')); e.add(new WebFXTreeItem('2.1.2')); e.add(new WebFXTreeItem('2.1.3')); d.add(new WebFXTreeItem('2.2')); d.add(new WebFXTreeItem('2.3')); d.add(new WebFXTreeItem('2.4')); document.write(tree); } function addNode() { if (tree.getSelected()) { tree.getSelected().add(new WebFXTreeItem('New')); } } function addNodes() { if (tree.getSelected()) { var foo = tree.getSelected().add(new WebFXTreeItem('New')); var bar = foo.add(new WebFXTreeItem('Sub 1')); var fbr = foo.add(new WebFXTreeItem('Sub 2')); } } function delNode() { if (tree.getSelected()) { tree.getSelected().remove(); } } </script>
打开关闭节点:tree.toggle() 打开节点:tree.expand(); 关闭节点:tree.collapse(); 打开所有节点:tree.expandAll(); 关闭所有节点:tree.collapseAll(); 打开子节点:tree.expandChildren(); 关闭子节点:tree.collapseChildren(); 显示当前节点的id:if (tree.getSelected()) { alert(tree.getSelected().id); } 增加节点:addNode() 增加多个节点:addNodes() 删除节点:delNode()