newxtree.js代码


Posted in Javascript onMarch 13, 2007

/*=========================================
        Powered by Fason
        Email: fason_pfx@hotmail.com
        HomePage:http://fason.nease.net
        Version:3.0
=========================================*/

var TreeConfig = {
    TreeIcon            :{
        root                :'root.gif',
        folderopen            :'folderopen.gif',
        folder                :'folder.gif',
        file                :'file.gif',
        Rplus                :'Rplus.gif',
        Rminus                :'Rminus.gif',
        join                :'T.gif',
        joinbottom            :'L.gif',
        plus                :'Tplus.gif',
        plusbottom            :'Lplus.gif',
        minus                :'Tminus.gif',
        minusbottom            :'Lminus.gif',
        blank                :'blank.gif',
        line                :'I.gif'
    },
    defaultText            :"New",
    defaultHref            :"javascript:void(0)",
    defaultTarget        :"_blank",
    loadingText            :"Loading...",
    unavaibleText        :"Unavaible",
    useCookie            :true,
    contextmenu            :null
};

var TreeHandler = {
    id                    :0,
    all                    :{},
    getId                :function (obj, key) {
        var ID = key == null ? this.id :key;
        this.all[ID] = obj;
        return key==null ? this.id++ : key;
    },
    setImagePath        :function(sPath){
        for (i in TreeConfig.TreeIcon) {
            var tem = new Image();
            tem.src = sPath + TreeConfig.TreeIcon[i];
            TreeConfig.TreeIcon[i] = tem.src;
        }
    }
};

//*************
//    WebCookie
//*************
var WebCookie = new function () {

    this.setValue = function (sName, sValue, sExpire, sPath, sDomain, sSecure) {
        var cookie = sName + "=" + escape(sValue);
        if (sExpire) cookie += "; expires=" + sExpire.toGMTString();
        if (sPath) cookie += "; path=" + sPath;
        if (sSecure) cookie += "; secure";
        document.cookie = cookie;
    };

    this.getValue = function (sName) {
        var c = document.cookie.split("; ");
        for (var i=0; i<c.length; i++) {
            var cItem = c[i].split("=");
            if (cItem[0] == sName) return unescape(cItem[1]);
        }
        return null;
    };

    this.delCookie = function (sName) {
        var cVal = this.getValue(sName);
        if (cVal != null) {
            var d = new Date();d.setTime(d.getTime()-1);
            this.setValue(sName, cVal, d);
        }
    };
};

//**************
// TreeNode
//**************
Array.prototype.Remove = function(o){
    for (var i=0; i<this.length; i++) {
        if (this[i] == o) break;
    }
    if (i != this.length) return this.slice(0,i).concat(this.slice(i+1,this.length));
    return this;
};

function TreeNode(sKey, sText, sHref, sTarget, sTitle, sIcon, sOpenIcon, sXMLSrc) {
    this.id            = TreeHandler.getId(this, sKey);
    this.level        = 0;
    this.text        = sText ? sText : TreeConfig.defaultText;
    this.href        = sHref ? sHref : TreeConfig.defaultHref;
    this.target        = sHref ? (sTarget ? sTarget : TreeConfig.defaultTarget) : "_self";
    this.title        = sTitle ? sTitle : this.text;
    this.childNodes    = new Array();
    this.parentNode    = null;
    this.open        = TreeConfig.useCookie ? this.getOpen() : 0;
    this.shown        = false;
    this.icon        = sIcon;
    this.openIcon    = sOpenIcon;
    this.src        = sXMLSrc;
    this._tree        = null;
    this.onexpand    = null;
    this.oncollapse    = null;
    this.onselect    = null;
    this.toElement();
    if (sXMLSrc) {
        this.open = 0;
        this.loader = new this.constructor(null, TreeConfig.loadingText, null, null, null);
        this.add(this.loader);
    }
};

TreeNode.prototype.toElement = function () {
    var f = typeof(this.href) == "function";
    var oThis = this;
    this._item = document.createElement("div");
    this._item.className = "TreeNode";
    this._item.noWrap = true;
    this._item.onselectstart = function(){ return false;}
    this._handler = document.createElement("img");
    this._handler.align = "absmiddle";
    this._handler.onclick = function(){ oThis.toggle();};
    this._item.appendChild(this._handler);
    this._icon = document.createElement("img");
    this._icon.align = "absmiddle";
    //this._icon.onclick = function(){ oThis.select(true); };
    this._icon.onclick = function(){ oThis.toggle(); };   //superj修改,单击图标为展开
    this._icon.ondblclick = function(){ oThis.toggle(); };
    this._item.appendChild(this._icon);
    this._anchor = document.createElement("a");
    this._anchor.className = "TreeNode-Anchor"
    this._anchor.innerHTML = this.HTMLtoText(this.text);
    this._anchor.target = f ? "_self" : this.target;
    this._anchor.href = f ? TreeConfig.defaultHref : this.href;
    this._anchor.title = this.title;
    //this._anchor.onmousedown = function(e){ return oThis.contextMenu(e); };
    this._anchor.onmousedown = function(){ oThis.toggle(); };   //superj修改,单击标签为展开
    this._anchor.onfocus = function(){ oThis.focus(); }
    this._anchor.onblur = function(){ oThis.blur(); };
    this._anchor.onkeydown = function(e){ return oThis.KeyDown(e);}
    this._item.appendChild(this._anchor);
    this._container = document.createElement("div");
    this._container.style.display = this.open ? "" : "none";
    this._item.appendChild(this._container);
};

TreeNode.prototype.HTMLtoText = function (s) {
    return String(s).replace(/&/g, "&").replace(/\"/g, '"').replace(/</g,'<').replace(/>/g, '>');
};

TreeNode.prototype.isLast = function () {
    var p = this.parentNode;
    if (p == null) return false;
    return p.childNodes[p.childNodes.length - 1] == this;
};

TreeNode.prototype.indent = function () {
    for (var i=0; i<this.childNodes.length; i++) { this.childNodes[i].indent(); }
    var t = this._item, iv = this.level;
    if (iv) while (--iv) { t.removeChild(t.firstChild); }
    var node = this.parentNode, v = 0, _root = this.getRoot();
    while (node) {
        v++;
        if (node == _root) break;
        var m = document.createElement("img");
        m.align = "absmiddle";
        m.src = node.isLast() ? TreeConfig.TreeIcon.blank : TreeConfig.TreeIcon.line;
        t.insertBefore(m, t.firstChild);
        node = node.parentNode;
    }
    this.level = v;
};

TreeNode.prototype.recalIndent = function (nLevel, b) {
    for (var i = 0; i<this.childNodes.length; i++) {
        this.childNodes[i]._item.childNodes[nLevel-1].src = b ? TreeConfig.TreeIcon.blank : TreeConfig.TreeIcon.line;
        this.childNodes[i].recalIndent(nLevel, b);
    }
};

TreeNode.prototype.reloadIcon = function () {
    var l = this.isLast(), o = this.open, m = TreeConfig.TreeIcon;
    if (this.parentNode) {
        this._handler.src = this.childNodes.length>0 ? (o ? (l ? m.minusbottom : m.minus) : (l ? m.plusbottom : m.plus)) : (l ? m.joinbottom : m.join);
    }
    this._icon.src = this.childNodes.length>0 ? (o ? (this.openIcon ? this.openIcon : (this.icon ? this.icon : m.folderopen)) : (this.icon ? this.icon : m.folder)) : (this.icon ? this.icon : m.file);
};

TreeNode.prototype.addXMLNodeLoop = function (doc) {
    var c = doc.childNodes;
    for (var i = 0; i < c.length; i++) {
        var o = c[i];
        if (o.nodeType == 1) {
            var X = this.constructor;
            var node = new X(o.getAttribute("id"), o.getAttribute("text"), o.getAttribute("href"), o.getAttribute("target"), o.getAttribute("title"), o.getAttribute("icon"), o.getAttribute("openicon"), o.getAttribute('src'));
            this.add(node);
            if (!o.getAttribute("src")) {
                node.addXMLNodeLoop(o);
            }
        }
    }
};

TreeNode.prototype.XMLHttpCallBack = function () {
    if (this._xmlhttp.readyState != 4) return;
    var oLoad = this.loader;
    var doc = this._xmlhttp.responseXML;
    var sXML = String(this._xmlhttp.responseText).replace(/<\?xml[^\?]*\?>/i, "");
    if (window.DOMParser) {
        doc = (new DOMParser()).parseFromString(sXML, 'text/xml');    
    } else {
        doc.loadXML(sXML);
    }
    if (doc.documentElement) {
        var oRoot = doc.getElementsByTagName("Tree")[0];
        if (oRoot.childNodes.length == 0) { this.setText(TreeConfig.unavaibleText); }
        else {
            var s = this._tree.getSelectedNode() == oLoad;
            this.addXMLNodeLoop(oRoot);
            oLoad.remove();
            this.async();
            this.loader = null;
        }
    }
    else {
        oLoad.setText(TreeConfig.unavaibleText);
    }
};

TreeNode.prototype.getXML = function () {
    var oLoad = this.loader;
    var oThis = this;
    this._xmlhttp = null;
    try{
        if (window.XMLHttpRequest) 
            this._xmlhttp = new XMLHttpRequest();
        else if (window.ActiveXObject)
            this._xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }catch (e){}
    if (this._xmlhttp == null) throw new Error('Your browser doesn\'t support!');
    this._xmlhttp.onreadystatechange = function () { oThis.XMLHttpCallBack(); };
    try {
        var temp = (/\?/g.test(this.src)?"&":"?") + "temp=" + String(new Date().getTime())
        this._xmlhttp.open("get", this.src + temp, true);
        this._xmlhttp.send(null);
    }catch(e){ oLoad.setText(TreeConfig.unavaibleText);}
};

TreeNode.prototype.resetTree = function (oTree) {
    for (var i=0; i<this.childNodes.length; i++)
        this.childNodes[i].resetTree(oTree);
    this._tree = oTree;
};

TreeNode.prototype.setOpen = function (v) {
    this.open = v;
    if (TreeConfig.useCookie) {
        WebCookie.setValue("o" + this.id, v);
    }
};

TreeNode.prototype.getOpen = function () {
    var o = WebCookie.getValue("o" + this.id);
    if (o != null)
        return parseInt(o);
    return 0;
};

TreeNode.prototype.toHTML = function() {
    var o = this._item;
    this.indent();
    this.reloadIcon();
    if (this.parentNode == null) o.removeChild(this._handler);
    return o;
};    

TreeNode.prototype.getRoot = function() {
    var root = this;
    while (root.parentNode) root = root.parentNode;
    return root;
};    

TreeNode.prototype.setText = function(sText) {
    this.text = sText;
    this._anchor.innerHTML = this.HTMLtoText(sText);
};

TreeNode.prototype.add = function(oItem) {
    var tree = this._tree;
    oItem.parentNode = this;
    var len = this.childNodes.length;
    this.childNodes[len] = oItem;
    if (len > 0) {
        var o = this.childNodes[len-1];
        o.recalIndent(o.level, false);
        o.reloadIcon();
    } else if (tree) {
        if (tree._rendered) this.open = 0;
        this.reloadIcon();
    }
    if (tree) this.resetTree(tree);
    this._container.style.display = this.open ? "" : "none";
    this._container.appendChild(oItem.toHTML());
    return oItem;
};

TreeNode.prototype.remove = function(f) {
    for (var i=0; i<this.childNodes.length; i++) { this.childNodes[i].remove(true); }
    this.unselect();
    var v = this.getPreviousSibling();
    var p = this.parentNode;
    if (p) {
        p.childNodes = p.childNodes.Remove(this);
        if (p.childNodes.length > 0) {
            var node = p.childNodes[p.childNodes.length-1];
            node.recalIndent(node.level, true);
            node.reloadIcon();
        } else {
            p.setOpen(0);
            p._container.style.display = "none";
            p.reloadIcon();
        }
    }
    var tmp = this._item;
    if (tmp) tmp.parentNode.removeChild(tmp);
    delete TreeConfig[this.id];
    if (v && !f) v.select(false);
};

TreeNode.prototype.toggle = function() {
    if (this.childNodes.length>0) {
        if (this.open) {
            this.collapse();
        }
        else {
            this.expand();
        }
    }
};

TreeNode.prototype.expand = function() {
    this.setOpen(1);
    if (! this.shown) {
        this.shown = true;
        if (this.src) this.getXML();
    }
    this.reloadIcon();
    this._container.style.display = "";
    if (typeof this.onexpand == "function") {
        this.onexpand();
    } else {
        eval(this.onexpand);
    }
};

TreeNode.prototype.collapse = function() {
    this.setOpen(0);
    this._container.style.display = "none";
    this.reloadIcon();
    this.select(false);
    if (typeof this.oncollapse == "function") {
        this.oncollapse();
    } else {
        eval(this.oncollapse);
    }
};

TreeNode.prototype.async = function () {
    var a = this._tree.context;
    if (!a.length) return;
    var id = a[a.length - 1];
    var node = TreeHandler.all[id];
    if (typeof(node) != 'undefined') {
        if (node.parentNode == this) {
            this._.context = a.slice(0, -1);
            if (node.childNodes.length > 0)
                node.expand();
            else 
                node.select();
        }
    }
};

TreeNode.prototype.expandAll = function() {
    if (this.childNodes.length>0 && !this.open) this.expand();
    this.expandChildren();
};

TreeNode.prototype.collapseAll = function() {
    this.collapseChildren();
    if (this.childNodes.length>0 && this.open) this.collapse();
};

TreeNode.prototype.expandChildren = function() {
    for (var i=0; i<this.childNodes.length; i++)
        this.childNodes[i].expandAll();
};

TreeNode.prototype.collapseChildren = function() {
    for (var i=0; i<this.childNodes.length; i++)
        this.childNodes[i].collapseAll();
};

TreeNode.prototype.openURL = function() {
    if (typeof this.href == "function") {
        this.href();
    } else if (this.href != TreeConfig.defaultHref) {
        window.open(this.href, this.target);
    }
};

TreeNode.prototype.select = function(b){
    this._anchor.focus();
    if (b) {
        this.openURL();
    }
};

TreeNode.prototype.unselect = function () {
    this._anchor.className = "TreeNode-Anchor";
    var selected = this._tree.getSelectedNode();
    if (selected == this) this._tree.setSelectedNode(null);
};

TreeNode.prototype.focus = function () {
    var node = this._tree.getSelectedNode();
    if (node && node != this) { node.unselect(); }
    this._tree.setSelectedNode(this);
    var oItem = this._anchor;
    oItem.className =  "TreeNode-Anchor focus";
    if (typeof this.onselect == "function") {
        this.onselect();
    } else {
        eval(this.onselect);
    }
};

TreeNode.prototype.blur = function () {
    var oItem = this._anchor;
    oItem.className =  "TreeNode-Anchor selected";
};

TreeNode.prototype.contextMenu = function (e) {
    e = e || window.event;
    if (e.button == 2) {
        if (typeof TreeConfig.contextmenu == "function")
            TreeConfig.contextmenu();
        return false;
    }
    return true;
};

TreeNode.prototype.getFirstChild = function() {
    if (this.childNodes.length>0 && this.open)
        return this.childNodes[0];
    return this;
};

TreeNode.prototype.getLastChild = function() {
    if (this.childNodes.length>0 && this.open)
        return this.childNodes[this.childNodes.length-1].getLastChild();
    return this;
};

TreeNode.prototype.getPreviousSibling = function() {
    if (!this.parentNode) return null;
    for (var i=0;i<this.parentNode.childNodes.length;i++)
        if (this.parentNode.childNodes[i] == this) break;
    if (i == 0) 
        return this.parentNode;
    else
        return this.parentNode.childNodes[i-1].getLastChild();
};

TreeNode.prototype.getNextSibling = function() {
    if (!this.parentNode) return null;
    for (var i=0;i<this.parentNode.childNodes.length;i++)
        if (this.parentNode.childNodes[i] == this)break;
    if (i == this.parentNode.childNodes.length-1)
        return this.parentNode.getNextSibling();
    else
        return this.parentNode.childNodes[i+1];
}

TreeNode.prototype.KeyDown=function(e){
    e = e || window.event;
    var code = e.which || e.keyCode;
    var o = this;
    if (code == 37) {
        if (this.open) this.collapse();
        else {
            if (this.parentNode) this.parentNode.select(false);
        }
        return false;
    }
    else if (code == 38) {
        var el = o.getPreviousSibling();
        if (el) el.select(false);
        return false;
    }
    else if (code == 39) {
        if (this.childNodes.length>0) {
            if (!this.open) this.expand();
            else {
                var el = o.getFirstChild();
                if(el) el.select(false);
            }
        }
        return false;
    }
    else if (code == 40) {
        if (this.open && this.childNodes.length>0) this.getFirstChild().select(false);
        else {
            var el = o.getNextSibling();
            if (el) el.select(false);
        }
        return false;
    }
    else if (code == 13) {
        this.toggle();
        return true;
    }
    return true;
};

function CheckBoxTreeNode(sKey, sName, sText, sHref, sTarget, sTitle, sIcon, sOpenIcon, sXMLSrc) {
    this._base = TreeNode;
    this._base(sKey, sText, sHref, sTarget, sTitle, sIcon, sOpenIcon, sXMLSrc);
    this.name = sName;
    this.checked = false;
};

CheckBoxTreeNode.prototype = new TreeNode;

CheckBoxTreeNode.prototype.toHTML = function () {
    this._base = TreeNode.prototype.toHTML;
    this._base();
    var oThis = this;
    this._checkbox = document.createElement("input");
    this._checkbox.id = this._checkbox.name = this.name;
    this._checkbox.type = "checkbox";
    this._checkbox.defaultChecked = this.parentNode instanceof CheckBoxTreeNode ? this.parentNode.getChecked() : this.checked;
    this._checkbox.onclick = function () { oThis.check() };
    this._checkbox.hideFocus = true;
    this._item.insertBefore(this._checkbox, this._icon);
    return this._item;
};

CheckBoxTreeNode.prototype.check = function () {
    this.setCheckedChildren(this.getChecked());
    this.setCheckedParent();
    if (typeof this.oncheck == "function") {
        this.oncheck();
    } else {
        eval(this.oncheck);
    }
};

CheckBoxTreeNode.prototype.setCheckedChildren = function (b) {
    for (var i=0,j=0; i<this.childNodes.length; i++) {
        if (this.childNodes[i] instanceof CheckBoxTreeNode) 
            this.childNodes[i].setCheckedChildren(b);
    } 
    this._checkbox.checked = b;
};

CheckBoxTreeNode.prototype.setCheckedParent = function () {
    var p = this.parentNode;
    if (p instanceof CheckBoxTreeNode) {
        for (var i=0; i<p.childNodes.length; i++) {
            if (!p.childNodes[i].getChecked()) break;
        }
        p._checkbox.checked = i == p.childNodes.length
        p.setCheckedParent();
    }
};

CheckBoxTreeNode.prototype.getChecked = function () {
    return this._checkbox.checked;
};

//************
// TreeView
//************
function TreeView(sKey, sText, sHref, sTarget, sTitle, sIcon, sOpenIcon, sXMLSrc) {
    this.base = TreeNode;
    this.base(sKey, sText, sHref, sTarget, sTitle, sIcon, sOpenIcon, sXMLSrc);
    this.icon = sIcon || TreeConfig.TreeIcon.root;
    this.context = new Array();
    this._rendered = false;
    this._tree = this;
};

TreeView.prototype = new TreeNode;

TreeView.prototype.getSelectedNode = function () {
    if (window.selectedNode) return window.selectedNode;
    return null;
};

TreeView.prototype.setSelectedNode = function (oNode) {
    window.selectedNode = oNode;
};

TreeView.prototype.setContext = function () {
    this.context = new Array();
    for (var i=arguments.length-1,j=0; i>=0; i--,j++) {
        this.context[j] = arguments[i];
    }
};

TreeView.prototype.create = function (oTarget) {
    oTarget.appendChild(this.toHTML());
    this._rendered = true;
    if (this.childNodes.length>0 || this.open || this.src) 
        this.expand();
};

TreeView.prototype.toString = function () {
    var obj = this.toHTML();
    var o = document.createElement("div");
    o.appendChild(obj);
    this._rendered = true;
    return o.innerHTML;
};

Javascript 相关文章推荐
JObj预览一个JS的框架
Mar 13 Javascript
用jQuery简化JavaScript开发分析
Feb 19 Javascript
用js来刷新当前页面保留参数的具体实现
Dec 23 Javascript
Javascript 读取操作Sql中的Xml字段
Oct 09 Javascript
学习JavaScript设计模式之状态模式
Jan 08 Javascript
jQuery实现点击后高亮背景固定显示的菜单效果【附demo源码下载】
Sep 21 Javascript
Node.js实现发送邮件功能
Nov 06 Javascript
VUE2.0+ElementUI2.0表格el-table实现表头扩展el-tooltip
Nov 30 Javascript
浅谈对于react-thunk中间件的简单理解
May 01 Javascript
vue cli3 配置proxy代理无效的解决
Oct 30 Javascript
浅谈JavaScript中你可能不知道URL构造函数的属性
Jul 13 Javascript
ElementUI实现el-form表单重置功能按钮
Jul 21 Javascript
xtree.js 代码
Mar 13 #Javascript
js资料prototype 属性
Mar 13 #Javascript
js资料toString 方法
Mar 13 #Javascript
pjblog修改技巧汇总
Mar 12 #Javascript
解决 firefox 不支持 document.all的方法
Mar 12 #Javascript
收藏一些不常用,但是有用的代码
Mar 12 #Javascript
图片自动缩小的js代码,用以防止图片撑破页面
Mar 12 #Javascript
You might like
php adodb连接mssql解决乱码问题
2009/06/12 PHP
php函数与传递参数实例分析
2014/11/15 PHP
php批量转换文件夹下所有文件编码的函数类
2017/08/06 PHP
js 实现在离开页面时提醒未保存的信息(减少用户重复操作)
2013/01/16 Javascript
Jquery Validate 正则表达式实用验证代码大全
2013/08/23 Javascript
jquery遍历checkbox介绍
2014/02/21 Javascript
js的image onload事件使用遇到的问题
2014/07/15 Javascript
深入理解JavaScript系列(28):设计模式之工厂模式详解
2015/03/03 Javascript
JavaScript 七大技巧(一)
2015/12/13 Javascript
学习掌握JavaScript中this的使用技巧
2016/08/29 Javascript
javascript跨域请求包装函数与用法示例
2016/11/03 Javascript
JS判断是否为JSON对象及是否存在某字段的方法(推荐)
2016/11/29 Javascript
利用yarn代替npm管理前端项目模块依赖的方法详解
2017/09/04 Javascript
Vue底层实现原理总结
2018/02/17 Javascript
实现高性能javascript的注意事项
2019/05/27 Javascript
JavaScript实现打字游戏
2021/02/19 Javascript
python matplotlib中文显示参数设置解析
2017/12/15 Python
python opencv读mp4视频的实例
2018/12/07 Python
对python产生随机的二维数组实例详解
2018/12/13 Python
Python多线程处理实例详解【单进程/多进程】
2019/01/30 Python
详解用Python练习画个美队盾牌
2019/03/23 Python
Pytorch之view及view_as使用详解
2019/12/31 Python
django自定义非主键自增字段类型详解(auto increment field)
2020/03/30 Python
python3爬虫中引用Queue的实例讲解
2020/11/24 Python
python实现文件+参数发送request的实例代码
2021/01/05 Python
25个CSS3动画按钮和菜单教程分享
2012/10/03 HTML / CSS
使用HTML5在网页中嵌入音频和视频播放的基本方法
2016/02/22 HTML / CSS
详解通过focusout事件解决IOS键盘收起时界面不归位的问题
2019/07/18 HTML / CSS
北美最大的手工艺品零售商之一:Michaels Stores
2019/02/27 全球购物
库存图片、照片、矢量图、视频和音乐:Shutterstock
2021/02/12 全球购物
机械工程师求职自我评价
2013/09/23 职场文书
人力管理专业毕业生求职信
2014/02/27 职场文书
敬老院义诊活动总结
2015/05/07 职场文书
教师节领导致辞
2015/07/29 职场文书
小学生教师节广播稿
2015/08/19 职场文书
如何利用python实现列表嵌套字典取值
2022/06/10 Python