如何用javascript创建html页面的treeview?

时间:2011-07-24 20:54:26

标签: javascript

如何使用javascript创建包含所有元素属性的html页面的树视图?

也许有人有榜样?

2 个答案:

答案 0 :(得分:0)

一个简单的实现。有很多优化和增强的空间。

var indentation = 0;
function printdom(el) {
    var cn = el.childNodes;
    if (cn.length) {
        console.log(spaces(indentation), '<' + el.tagName + attributes(el) +'>');
        indentation++;
        for (var i = 0; i < cn.length; i++) {
            if (cn[i].tagName) {
                printdom(cn[i]);
            } else {
                console.log(spaces(indentation), cn[i].textContent);
            }
        }
        indentation--;
        console.log(spaces(indentation), '</' + el.tagName + '>');
    } else {
        console.log(spaces(indentation), '<' + el.tagName + attributes(el) +'/>');
    }
}

function attributes(el) {
    var result = '';
    var attrs = el.attributes;
    for (var i = 0; i < attrs.length; i++) {
        result += ' ' + attrs.item(i).nodeName + '="' + attrs.item(i).nodeValue + '"';
    }
    return result;
}

function spaces(indentation) {
    return new Array(indentation + 1).join('    ');
}

printdom(document.documentElement);

答案 1 :(得分:0)

另一个简单的实现。

  • 您可以将任何元素添加到树枝中。
  • 您可以设置分支的打开和关闭动画。
  • 您可以在一行中显示分支。

Demo

&#13;
&#13;
function consoleLog(message) { console.log(message); }
function consoleError(message) {
    alert(message);
    //console.error(message);
}
var myTreeView = {
    createTree: function (elTree, tree) {
        tree.forEach(function (branch) {
            myTreeView.appendBranch(elTree, branch)
        });
    },
    createBranch: function (options)
    {
        var el = document.createElement((typeof options.tagName == 'undefined') ? "div" : options.tagName);
        el.innerHTML =
            '<span class="treeView" onclick="javascript: myTreeView.onclickBranch(this)" '
                    + ((typeof options.title == 'undefined') ? '' : 'title="' + options.title + '"') + '>'
                + '<span class="triangle">▶</span>'
                + '<span class="name">' + options.name + '</span>'
            + '</span>'
        ;
        var elA = el.querySelector('.treeView');
        elA.params = options.params;
        return el;
    },
    onclickBranch: function (a) {
        //consoleLog("onclickBranch()");
        var elBranch = a.parentElement.querySelector('.branch')
        var triangle;
        var isOpened = elBranch ?
            (
                (elBranch.className.indexOf('b-toggle') == -1) ?
                true :
                ((elBranch.className.indexOf(' expanded') != -1) ? true : false)
            )
            : false;
        if (isOpened) {
            if (a.branchElement.className.indexOf('b-toggle') != -1)
                a.branchElement.className = a.branchElement.className.replace(' expanded', '');
            else a.parentElement.removeChild(elBranch);
            triangle = '▶';
            isOpened = false;
            if (typeof a.params.onCloseBranch != 'undefined')
                a.params.onCloseBranch(a);
        } else {
            if (typeof a.branchElement == 'undefined')
                a.branchElement = a.params.createBranch();
            if (!elBranch) {
                if (a.branchElement.className.indexOf(' branch') == -1)
                    a.branchElement.className += ' branch';
                a.parentElement.appendChild(a.branchElement);
            }

            if (a.branchElement.className.indexOf('b-toggle') != -1)
                a.branchElement.className += ' expanded';

            triangle = '▼';
            isOpened = true;
            if (typeof a.params.onOpenBranch != 'undefined')
                a.params.onOpenBranch(a);
        }
        a.querySelector('.triangle').innerHTML = triangle;
        return isOpened;
    },
    appendBranch: function (elTree, branch) {
        elTree.appendChild(myTreeView.createBranch(
            {
                name: branch.name,
                params:
                {
                    createBranch: function () {
                        if (typeof branch.branch == "function")
                            return branch.branch();
                        else {
                            var el = document.createElement("div");
                            el.className = "branchLeft" + (branch.animate ? " b-toggle" : "");
                            var res = false;
                            if (typeof branch.branch == "string") {
                                el.innerText = branch.branch;
                                res = true;
                            }
                            if (this.tree) {
                                this.tree.forEach(function (branch) {
                                    myTreeView.appendBranch(el, branch);
                                });
                                res = true;
                            }
                            if (!res)
                                consoleError("Invalid branch");
                            return el;
                        }
                    },
                    tree: branch.tree
                },
                title: branch.title,
                tagName: branch.tagName
            }
        ));
    }
}
try{
           document.getElementById("SimpleTree").appendChild(myTreeView.createBranch(
                {
                    name: "Simple Tree",
                    params:
                    {
                        createBranch: function () {
                            var el = document.createElement("div");
                            el.className = "branchLeft";
                            el.innerText = "Branch";
                            return el;
                        }
                    }
                }));
            document.getElementById("SimpleTree2").appendChild(myTreeView.createBranch(
                {
                    name: "Open Branch",
                    params:
                    {
                        createBranch: function () {
                            var el = document.createElement("div");
                            el.className = "branchLeft";
                            el.innerText = "Branch";
                            return el;
                        },
                        onOpenBranch: function (a) { a.querySelector(".name").innerText = "Close Branch"; },
                        onCloseBranch: function (a) { a.querySelector(".name").innerText = "Open Branch"; }
                    }
                }));
            myTreeView.createTree(
                document.getElementById("ComplexTree"),
                [
                    {
                        name: "Animate Branch",
                        branch: "branch 1",
                        animate: true,
                        tree: [
                            {
                                name: "tree 2.1",
                                animate: true,
                                tree: [
                                    {
                                        name: "tree 2.2",
                                        branch: "branch 2.2",
                                        animate: true
                                    }
                                ]
                            }
                        ]
                    },
                    {
                        name: "Complex Tree 2",
                        branch: function () {
                            var el = document.createElement("div");
                            el.className = "branchLeft";
                            el.appendChild(document.createElement("input"));
                            return el;
                        },
                        title: "inline-element",
                        tagName: "span"
                    },
                    {
                        name: "Complex Tree 3",
                        branch: "branch 3",
                        title: "inline-element",
                        tagName: "span"
                    }
                ]
            );
        } catch (e) {
            consoleError(e.message);
        }
&#13;
.treeView {
	cursor: pointer;
    font-weight: bold;
    text-decoration: underline;
}
.branchLeft {
    margin-left: 10px;
}

/* thanks to http://jsfiddle.net/FtL6G/ */
.b-toggle {
    opacity: 0;
    max-height: 0;
    overflow: auto;/*hidden;*/
    -moz-transition: opacity 1s, max-height 1s;
    -ms-transition: opacity 1s, max-height 1s;
    transition: opacity 1s, max-height 1s;
    _display: none;
}
.expanded {
    max-height: 1000px;
    opacity: 1;
    _display: block;
}
&#13;
<p><a href='https://github.com/anhr/TreeElement' target="_blank">GitHub</a></p>

<!--Simple Tree-->
<h2 >Simple Tree</h2>
<div id="SimpleTree"></div>
<h2>Simple Tree 2</h2>
<div id="SimpleTree2"></div>

<!--Complex Tree-->
<h2>Complex Tree</h2>
<div id="ComplexTree"></div>
&#13;
&#13;
&#13;