解决ExtJS TreePanel 的 iconCls设置问题

来源:互联网 发布:北京精雕编程教程 编辑:程序博客网 时间:2024/04/19 20:23

很久没有写代码了,最近在做一个在线帮助网站,于是又捡起了 ExtJS,我用 TreePanel 做为左边栏的导航树,我希望能够根据节点指向的内容来定义节点的图标,如以下的样子:

展开节点以前

 

展开节点以后

 

如果节点包含有子节点,则该节点就有 “展开” 和 “关闭” 这两种状态,我希望能过通过设置自己的样式表来控制指定节点的这两种状态下的图标,就如上图那样。

查看了 ExtJS 的帮助文档,文档提到 Ext.Tree.Panel 有一个 iconCls 设置项,但寥寥数语,没有详细的介绍如何使用,更没有提供范例代码:


于是我在节点数据中添加了这个属性(我借用了ExtJS 提供的范例 layout-browser 来测试),并参考了网站上搜索到的许多方法试着去实现这个效果,节点数据如下所示:

 

但却发现,无论我怎么定义 CSS ,均不能实现我所需要的效果,通过以下样式定义,只能设置节点 “关闭” 状态的图标,一旦展开节点,图标仍是默认的文件夹

 

样式表如下:


也就是只有 .myicon {...},和 .myicon2 {...}, 这两行定义有效,第二行定义展开节点样式的设置没有起作用,尽管网上提供了许多的范例,逐一试过均无效果(我用的是 ExtJS 4.1.0,不知道是不是版本的问题)。

于是开始分析 ExtJS 的代码了,在  ext-all-dev.js 找到定义节点图标样式的代码(打开文件,用  “expandedCls” 关键字搜索可以找到相应的代码段 ),分析后我认为,ExtJS 没有很好的处理 iconCls 这个属性,我们需要做一点修改,红色框部分是我添加的代码,添加后问题解决了,而且从原来的代码看,这里应该还定义了叶子节点(leaf 为 true 的节点 )和节点加载数据时的图标状态,这里我仅对节点的 “展开” 和 “关闭” 这两种状态做了测试,其他的大家可以自己尝试一下。


附:

Json代码:

[javascript] view plaincopy
{  
text: '.', 
children: [{ 
    text:'Basic Ext Layouts', 
    iconCls:'myicon', 
    expanded: false, 
    children:[{ 
        text:'Absolute', 
        id:'absolute', 
        iconCls: 'myicon2', 
        leaf:true 
    }] 
},{ 
    text:'Custom Layouts', 
    children:[{ 
        text:'Center', 
        id:'center', 
        leaf:true 
    }] 
},{ 
    text:'Combination Examples', 
    iconCls:'myicon2', 
    children:[{ 
        text:'Absolute Layout Form', 
        id:'abs-form', 
        leaf:true 
    },{ 
        text:'Tabs with Nested Layouts', 
        id:'tabs-nested-layouts', 
        leaf:true 
    }] 
}] 

样式表设置代码:
[css] 
.myicon {background-image: url(images/spellcheck.png)} 
.x-grid-tree-node-expanded .myicon 

  /* the icon */ 
  background-image: url(images/printer.png); 

 
.myicon2 {background-image: url(images/page_attach.png)} 
.x-grid-tree-node-expanded .myicon2 

  /* the icon */ 
  background-image: url(images/disk.png); 

修改代码段:

[javascript] 
for (; i < len; i++) { 
    row = rows[i]; 
    record = records[i]; 
    if (record.get('qtip')) { 
        row.rowAttr = 'data-qtip="' + record.get('qtip') + '"'; 
        if (record.get('qtitle')) { 
            row.rowAttr += ' ' + 'data-qtitle="' + record.get('qtitle') + '"'; 
        } 
    } 
    if (record.isExpanded()) { 
        row.rowCls = (row.rowCls || '') + ' ' + this.expandedCls; 
    } 
    if (record.isLeaf()) { 
        row.rowCls = (row.rowCls || '') + ' ' + this.leafCls; 
    } 
    if (record.isLoading()) { 
        row.rowCls = (row.rowCls || '') + ' ' + this.loadingCls; 
    } 
    if (record.get('iconCls').length > 0) { 
        row.rowCls = (row.rowCls || '') + ' ' + record.get('iconCls'); 
    } 

作者:sz_gambol

0 0