dTree树型组件详解

dTree树型组件详解1 文件组成图标文件,统一放在img文件夹内,包含树形节点的各种图标如文件夹、节点展开、节点关闭、根节点、链接线等。dtree.css文件,对树型显示的文字、鼠标点击、鼠标移入移出、链接等样式进行设置。dtree.js文件,生成树型组件,并对事件进行响应。使用步骤:首先,应建立一个树对象(n

大家好,欢迎来到IT知识分享网。dTree树型组件详解"

1 文件组成

  • 图标文件,统一放在img文件夹内,包含树形节点的各种图标如文件夹、节点展开、节点关闭、根节点、链接线等。
  • dtree.css文件,对树型显示的文字、鼠标点击、鼠标移入移出、链接等样式进行设置。
  • dtree.js文件,生成树型组件,并对事件进行响应。使用步骤:
    • 首先,应建立一个树对象(new dTree(‘d’))
    • 其次,向名称为’d’的树对象中添加节点(d.addNode(id))
    • 最后,向浏览器输出HTML页面(doucument.write(d),相当于隐式调用了document.write(d.toString()),toString()类似程序入口函数(与java类重写toString()类似)

2 dtree.js文件详解

2.1 树节点对象

// Node object节点对象
function Node(id, pid, name, url, title, target, icon, iconOpen, open) {
    this.id = id;//该节点ID
    this.pid = pid;//该节点的父节点ID
    this.name = name;//该节点名称
    this.url = url;//该节点的链接url
    this.title = title;//鼠标移到该节点上显示的热点标题文字
    this.target = target;//该节点链接打开的目标框架
    this.icon = icon;//该节点关闭状态图标
    this.iconOpen = iconOpen;//该节点打开状态图标
    this._io = open || false;//该节点是否打开标志,默认关闭(因此时open为undefined即为false)
    this._is = false;//该节点是否被选择标志
    this._ls = false;//该节点是否是最后一个兄弟节点标志
    this._hc = false;//该节点是否有孩子节点标志
    this._ai = 0;该节点位于节点数组中的位置索引号,默认为0
    this._p;//指向该节点的父节点
};

2.2 树对象

// Tree object树对象
function dTree(objName) {
    this.config = {
        target        : null,//该节点链接所打开的目标frame(_blank, _parent, _self, _top)
        folderLinks   : true, //文件夹节点有超链地址,点击,true则直接打开超链而不展开节点,false则忽略超链、展开或折叠节点;
        useSelection  : true,// 是否高亮显示选中的节点
useCookies :
true, //是否使用Cookies保存节点状态 useLines : true,//是否使用线段连接缩进 useIcons : true,//是否使用图标 useStatusText : false,//是否在状态栏显示提示文字(节点的名称) closeSameLevel: false,//是否只展开一个同级节点 inOrder : false //如在this.aNodes[]中始终按照父节点在前子节点在后存储,设置true可直接从父节点索引位置后进行查找子节点以提高效率 } this.icon = { root : 'img/base.gif', folder : 'img/folder.gif', folderOpen : 'img/folderopen.gif', node : 'img/page.gif', empty : 'img/empty.gif', line : 'img/line.gif', join : 'img/join.gif', joinBottom : 'img/joinbottom.gif', plus : 'img/plus.gif', plusBottom : 'img/plusbottom.gif', minus : 'img/minus.gif', minusBottom : 'img/minusbottom.gif', nlPlus : 'img/nolines_plus.gif', nlMinus : 'img/nolines_minus.gif' }; this.obj = objName;//树对象名称 this.aNodes = [];//存储树节点数据的数组 this.aIndent = [];//当父节点下是最后一个兄弟节点时,push(1),否则push(0) this.root = new Node(-1);//树的唯一根节点,ID值为-1 this.selectedNode = null;//选中节点的ID或所在this.aNode[]中的索引值this._ai this.selectedFound = false;//有否选中的节点标志 this.completed = false;//树HTML构建完成 };

 2.2.1 通过JavaScript 原型对象(prototype)为树对象(dTree)添加方法和属性

2.2.1.1 创建新节点并将其添加到树对象属性this.aNodes[ ]数组中
// Adds a new node to the node array 创建一个新节点并将其添加到this.aNodes[]尾部
dTree.prototype.add = function(id, pid, name, url, title, target, icon, iconOpen, open) {
    this.aNodes[this.aNodes.length] = new Node(id, pid, name, url, title, target, icon, iconOpen, open);
};
2.2.1.2 创建树结构并构建HTML输出到浏览器
// Outputs the tree to the page
//类似Java的类toString()重写,改变树对象的输出样式,可隐式调用
dTree.prototype.toString = function() { var str = '<div class="dtree">\n'; if (document.getElementById) {//document.getElementById,早期一些浏览器不支持,则会返回空属性 if (this.config.useCookies) this.selectedNode = this.getSelected();//从cookies中获取节点信息 str += this.addNode(this.root);//创建树结构HTML } else str += 'Browser not supported.'; str += '</div>'; if (!this.selectedFound) this.selectedNode = null;//如没有找到选中的节点,将索引位置置空 this.completed = true;//输出到page的HTML构建完成标志 return str; };
2.2.1.3 创建树结构HTML
// Creates the tree structure
dTree.prototype.addNode = function(pNode) {
    var str = '';
    var n=0; 
    if (this.config.inOrder) n = pNode._ai;//如this.aNodes[]节点严格按照父节点在前,子节点在后存储,则只须遍历父节点以后的部分数组数据
    for (n; n<this.aNodes.length; n++) {
        if (this.aNodes[n].pid == pNode.id) {//遍历this.aNodes[],仅处理pNode的子节点
            var cn = this.aNodes[n];//临时变量,将pNode子节点存储起来
            cn._p = pNode;//设置子节点指向父节点pNode
            cn._ai = n;//设置子节点在this.aNodes[]中索引值
            this.setCS(cn);//检查子节点是否还有子节点,是否是最后一个兄弟节点,并设置this.ls,this._hc
            if (!cn.target && this.config.target) cn.target = this.config.target;//设置目标Frame
            if (cn._hc && !cn._io && this.config.useCookies) cn._io = this.isOpen(cn.id);//设置节点开关标志
            if (!this.config.folderLinks && cn._hc) cn.url = null;//设置文件夹链接
            if (this.config.useSelection && cn.id == this.selectedNode && !this.selectedFound) {设置选中节点高亮显示
                    cn._is = true;
                    this.selectedNode = n;
                    this.selectedFound = true;
            }
            str += this.node(cn, n);//创建节点的图标、url和文本的HTML,【在this.node(cn,n)中又调用this.addNode(node),递归结束是节点没有孩子节点】
            if (cn._ls) break;//如已找到pNode节点下最后一个子节点,则结束遍历
        }
    }
    return str;
};
2.2.1.4 创建树节点的图标、url和文本的HTML
// Creates the node icon, url and text创建节点的图标、url和文本HTML
dTree.prototype.node = function(node, nodeId) {
    var str = '<div class="dTreeNode">' + this.indent(node, nodeId);
    if (this.config.useIcons) {//配置选择节点使用图标
        if (!node.icon) {//设置节点关闭时图标:是根节点设置为root,是有孩子的节点设置为folder,是没孩子节点设置为node(page.gif)
       node.icon = (this.root.id == node.pid) ? this.icon.root : ((node._hc) ? this.icon.folder : this.icon.node);
     }
if (!node.iconOpen) {//设置节点展开时的图标:有孩子节点设置为folderopen,无孩子节点设置为node
       node.iconOpen = (node._hc) ? this.icon.folderOpen : this.icon.node;
     }
if (this.root.id == node.pid) {//是根节点单独处理,开闭图标均设置为root node.icon = this.icon.root; node.iconOpen = this.icon.root; }
     //1. 构建icon图标即<img>标签:
     //id="i+对象名+传入节点在this.aNodes[]的位置索引号nodeId"(能确保唯一)
     //根据node._io标志,设置图标引入 str
+= '<img id="i' + this.obj + nodeId + '" src="' + ((node._io) ? node.iconOpen : node.icon) + '" alt="" />'; } if (node.url) {//配置节点使用url:
     //2.构建url即<a>标签:
     //id="s+对象名+传入节点在this.aNodes[]的位置索引号nodeId(能确保唯一),
     //根据useSelection与node._is标志设置class="nodeSel"或"node"
     //根据node.url设置href链接地址 str
+= '<a id="s' + this.obj + nodeId + \
         '" class="' + ((this.config.useSelection) ? ((node._is ? 'nodeSel' : 'node')) : 'node') + \
         '" href="' + node.url + '"';
if (node.title) str += ' title="' + node.title + '"';//根据node.title配置当鼠标位于节点上显示的热点文字 if (node.target) str += ' target="' + node.target + '"';//根据node.target配置超链打开的目标frame if (this.config.useStatusText) {//根据useStatusText配置鼠标位于节点上浏览器状态栏显示节点名称,鼠标移出时显示空白
       str += ' onmouseover="window.status=\'' + node.name + '\';return true;" onmouseout="window.status=\'\';return true;" ';
     }
if (this.config.useSelection && ((node._hc && this.config.folderLinks) || !node._hc))//配置选中节点高亮显示并响应鼠标点击事件 str += ' onclick="javascript: ' + this.obj + '.s(' + nodeId + ');"';//鼠标单击调用this.s(nodeId) str += '>'; } else if ((!this.config.folderLinks || !node.url) && node._hc && node.pid != this.root.id)//不允许使用url,配置节点响应鼠标事件 str += '<a href="javascript: ' + this.obj + '.o(' + nodeId + ');" class="node">';//鼠标单机调用this.o(nodeId) str += node.name;//配置节点名称为节点显示文字 if (node.url || ((!this.config.folderLinks || !node.url) && node._hc)) str += '</a>'; str += '</div>';
  
if (node._hc) {//节点存在孩子,递归创建孩子节点的图标、url和文本的HTML str += '<div id="d' + this.obj + nodeId + '" class="clip" style="display:' + ((this.root.id == node.pid || node._io) ? 'block' : 'none') + ';">'; str += this.addNode(node);//递归调用 str += '</div>'; } this.aIndent.pop();//清除this.aIndent[]中该节点前的是空白图标还是线图标记录 return str; };
2.2.1.5 判断数组this.aIndent[ ]对应设置,为节点前配置竖线或者空白图标
// Adds the empty and line icons
dTree.prototype.indent = function(node, nodeId) {
    var str = '';
    if (this.root.id != node.pid) {//不是根节点
        for (var n=0; n<this.aIndent.length; n++)//随递归之回归时进行进行配置
            str += '<img src="' + ( (this.aIndent[n] == 1 && this.config.useLines) ? this.icon.line : this.icon.empty ) + '" alt="" />';
        (node._ls) ? this.aIndent.push(0) : this.aIndent.push(1);//是最后一个兄弟节点(根节点是最后一个兄弟节点)push(0),否则push(1)

        if (node._hc) {
            str += '<a href="javascript: ' + this.obj + '.o(' + nodeId + ');"><img id="j' + this.obj + nodeId + '" src="';
            if (!this.config.useLines) str += (node._io) ? this.icon.nlMinus : this.icon.nlPlus;
            else str += ( (node._io) ? ((node._ls && this.config.useLines) ? this.icon.minusBottom : this.icon.minus) : ((node._ls && this.config.useLines) ? this.icon.plusBottom : this.icon.plus ) );

            str += '" alt="" /></a>';
        } else str += '<img src="' + ( (this.config.useLines) ? ((node._ls) ? this.icon.joinBottom : this.icon.join ) : this.icon.empty) + '" alt="" />';
    }
    return str;
};
 2.2.1.6 获取cookies中记录的选中节点
// Returns the selected node
dTree.prototype.getSelected = function() {
    var sn = this.getCookie('cs' + this.obj);
    return (sn) ? sn : null;
};
 2.2.1.7 从一条cookies中记录获取其值
// [Cookie] Gets a value from a cookie
dTree.prototype.getCookie = function(cookieName) {
    var cookieValue = '';
    var posName = document.cookie.indexOf(escape(cookieName) + '=');//对传入的cookieName编码并与'='连接作为查找字符串,取得首字符出现的索引号
    if (posName != -1) {
        var posValue = posName + (escape(cookieName) + '=').length;//取得cookieName值出现的首字符的索引号
        var endPos = document.cookie.indexOf(';', posValue);//取得cookieName值结束的索引号
        if (endPos != -1) cookieValue = unescape(document.cookie.substring(posValue, endPos));//截取cookie Name的值并解码
        else cookieValue = unescape(document.cookie.substring(posValue));//cookieName位于最后一条,则直接截取到末尾并对其解码
    }
    return (cookieValue);
};
2.2.1.8 将选中节点的ID组装成字符串并对对应cookie进行更新
// [Cookie] Returns ids of open nodes as a string
dTree.prototype.updateCookie = function() {
    var str = '';
    for (var n=0; n<this.aNodes.length; n++) {
        if (this.aNodes[n]._io && this.aNodes[n].pid != this.root.id) {
            if (str) str += '.';
            str += this.aNodes[n].id;
        }
    }
    this.setCookie('co' + this.obj, str);
};
2.2.1.9 向cookie写入值
// [Cookie] Sets value in a cookie
dTree.prototype.setCookie = function(cookieName, cookieValue, expires, path, domain, secure) {
    document.cookie =
        escape(cookieName) + '=' + escape(cookieValue)
        + (expires ? '; expires=' + expires.toGMTString() : '')
        + (path ? '; path=' + path : '')
        + (domain ? '; domain=' + domain : '')
        + (secure ? '; secure' : '');
};
2.2.1.10 清除cookie
// [Cookie] Clears a cookie
dTree.prototype.clearCookie = function() {
    var now = new Date();
    var yesterday = new Date(now.getTime() - 1000 * 60 * 60 * 24);
    this.setCookie('co'+this.obj, 'cookieValue', yesterday);
    this.setCookie('cs'+this.obj, 'cookieValue', yesterday);
};
 2.2.1.11 查找一个节点是否在cookie中
// [Cookie] Checks if a node id is in a cookie
dTree.prototype.isOpen = function(id) {
    var aOpen = this.getCookie('co' + this.obj).split('.');
    for (var n=0; n<aOpen.length; n++)
        if (aOpen[n] == id) return true;
    return false;
};
2.2.1.12 展开所有节点
// Open/close all nodes
dTree.prototype.openAll = function() {
    this.oAll(true);
};
2.2.1.13 关闭所有节点
// Open/close all nodes
dTree.prototype.closeAll = function() { this.oAll(false); };
 2.2.1.14 展开/关闭所有节点
// Open or close all nodes
dTree.prototype.oAll = function(status) {
    for (var n=0; n<this.aNodes.length; n++) {
        if (this.aNodes[n]._hc && this.aNodes[n].pid != this.root.id) {
            this.nodeStatus(status, n, this.aNodes[n]._ls)
            this.aNodes[n]._io = status;
        }
    }
    if (this.config.useCookies) this.updateCookie();
};
 2.2.1.15 关闭特定节点同级的所有节点
// Closes all nodes on the same level as certain node
//关闭特定节点(即有孩子的节点)除当前节点外同级的所有节点,有且仅有当前节点处于展开状态
dTree.prototype.closeLevel = function(node) { for (var n=0; n<this.aNodes.length; n++) { if (this.aNodes[n].pid == node.pid && this.aNodes[n].id != node.id && this.aNodes[n]._hc) { this.nodeStatus(false, n, this.aNodes[n]._ls); this.aNodes[n]._io = false; this.closeAllChildren(this.aNodes[n]); } } }
2.2.1.17 关闭所有孩子节点
// Closes all children of a node
dTree.prototype.closeAllChildren = function(node) {
    for (var n=0; n<this.aNodes.length; n++) {
        if (this.aNodes[n].pid == node.id && this.aNodes[n]._hc) {
            if (this.aNodes[n]._io) this.nodeStatus(false, n, this.aNodes[n]._ls);
            this.aNodes[n]._io = false;
            this.closeAllChildren(this.aNodes[n]); //通过递归调用,直到该节点没有孩子节点
        }
    }
}
2.2.1.18 展开树中指定的节点
// Opens the tree to a specific node
//nId--节点的ID(不是在this.aNode[]的索引值) bSelect--展开节点是否选中 bFirst--是否首次折叠 dTree.prototype.openTo = function(nId, bSelect, bFirst) { if (!bFirst) {//不是首次展开,就通过节点nId在this.aNode[]数组中查找存储该节点对象的位置的索引值,否则不再查找而直接通过索引获取节点对象 for (var n=0; n<this.aNodes.length; n++) { if (this.aNodes[n].id == nId) { nId=n; break; } } } var cn=this.aNodes[nId];//通过节点的存储位置索引值获取节点对象 if (cn.pid==this.root.id || !cn._p) return; cn._io = true; cn._is = bSelect; if (this.completed && cn._hc) this.nodeStatus(true, cn._ai, cn._ls); if (this.completed && bSelect) this.s(cn._ai); else if (bSelect) this._sn=cn._ai; this.openTo(cn._p._ai, false, true);//递归调用逐级展开父节点直到根节点或父节点引用为空 };
 2.2.1.19 改变节点状态(展开或关闭)
// Change the status of a node(open or closed)
//输出到HTML页面的树是按层输出的,每层被一个Id="d+this.obj+id"的div块包裹
//首先处理有孩子节点在展开或关闭状态的对应图标配置,然后设置包裹的div显示或隐藏来实现节点的展开或关闭
//status--当前节点的状态 id--当前节点在this.aNodes数组中的索引值 bottom--当前节点是否是最后一个兄弟节点 dTree.prototype.nodeStatus
= function(status, id, bottom) { eDiv = document.getElementById('d' + this.obj + id);//获取包裹的div块元素 eJoin = document.getElementById('j' + this.obj + id);//获取有孩子节点的连接图标(+/-)的img元素 if (this.config.useIcons) { eIcon = document.getElementById('i' + this.obj + id);//获取有孩子节点的图标 eIcon.src = (status) ? this.aNodes[id].iconOpen : this.aNodes[id].icon;//设置对应的展开或关闭图标 } eJoin.src = (this.config.useLines)?//设置对应的展开或关闭图标 ((status)?((bottom)?this.icon.minusBottom:this.icon.minus):((bottom)?this.icon.plusBottom:this.icon.plus))://使用连接线图标 ((status)?this.icon.nlMinus:this.icon.nlPlus);//不使用连接线图标时,配置对应的图标 eDiv.style.display = (status) ? 'block': 'none';//显示或隐藏该节点所在的块,实现展开或关闭 };
 2.2.1.20 从cookie中获取被选中的节点
// Returns the selected node
dTree.prototype.getSelected = function() {
    var sn = this.getCookie('cs' + this.obj);
    return (sn) ? sn : null;
};
2.2.1.21 高亮显示被选中的节点
// Highlights the selected node
dTree.prototype.s = function(id) {
    if (!this.config.useSelection) return;
    var cn = this.aNodes[id];
    if (cn._hc && !this.config.folderLinks) return;
    if (this.selectedNode != id) {
        if (this.selectedNode || this.selectedNode==0) {
            eOld = document.getElementById("s" + this.obj + this.selectedNode);
            eOld.className = "node";
        }
        eNew = document.getElementById("s" + this.obj + id);
        eNew.className = "nodeSel";
        this.selectedNode = id;
        if (this.config.useCookies) this.setCookie('cs' + this.obj, cn.id);
    }
};
2.2.1.22 考虑早期版本浏览器对数据类型Array可能没有定义push(),pop()方法而声明
// If Push and pop is not implemented by the browser如果浏览器未实现数组的push(),pop()方法则实现它们,在本程序中配合使用,后进先出
if
(!Array.prototype.push) { Array.prototype.push = function array_push() { for(var i=0;i<arguments.length;i++)//JavaScript 函数有个内置的对象 arguments 对象,它包含了函数调用的参数数组。
this[this.length]=arguments[i];//push()每次被调用的参数都保存在arguments对象数组中,将其拷贝到调用数组中(如this.aIndent[])
     return this.length;
}
};
if (!Array.prototype.pop) {
    Array.prototype.pop = function array_pop() {
        lastElement = this[this.length-1];//取出尾部的数据
        this.length = Math.max(this.length-1,0);//删除最后一个数据,如只有一个数据,则置空数组
        return lastElement;
    }
};

 

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/30735.html

(0)

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

关注微信