浅谈datagrid详细操作单元格样式

http://www.easyui.info/archives/470.html

今天有朋友问到:“如果设置列标题居中而列内容居右显示?”,仔细查了一下api,目前版本提供了两个相关的列属性,align和styler。align属性设置后会让列标题和列内容的对齐方式一致,而styler是作用于列内容上的,只是可惜了,styler只能定位到td元素,而真正决定列内容样式的是td下的div元素。

对于这种问题,我们应该也经常遇到。其实利用jQuery的强大选择器,要操作到每个单元格都很容易,所以解决这个问题的思路也很简单,在数据加载完以后(这时候内容单元格才形成),我们查找具体的列或者单元格,然后定义每个单元格的样式,所以定义一下align属性和onLoadSuccess事件就可以了:

实现代码:

 
  1. $('#tt').datagrid({   
  2.     url: 'datagrid_data2.json',   
  3.     title: 'DataGrid - ContextMenu',   
  4.      700,   
  5.     height: 'auto',   
  6.     fitColumns: true,   
  7.     columns: [[   
  8.         {field: 'itemid',title: 'Item ID', 80},   
  9.         {field: 'productid',title: 'Product ID', 120},    
  10.         {field: 'listprice',title: 'List Price', 80,align: 'right'},    
  11.         {field: 'unitcost',title: 'Unit Cost', 80,align: 'center'},    
  12.         {field: 'attr1',title: 'Attribute', 250},    
  13.         {field: 'status',title: 'Status', 60,align: 'center'}   
  14.     ]],   
  15.     onLoadSuccess: function(data){   
  16.         var panel = $(this).datagrid('getPanel');   
  17.         var tr = panel.find('div.datagrid-body tr');   
  18.         tr.each(function(){   
  19.             var td = $(this).children('td[field="unitcost"]');   
  20.             td.children("div").css({   
  21.                 "text-align": "right"  
  22.             });   
  23.             ;   
  24.         });   
  25.     }   
  26. });  

onLoadSuccess事件里面我们操作了内容单元格,标题单元格也很容易操作,只要将tr的查找方式变为以下形式即可:

 
  1. var tr = panel.find('div.datagrid-header tr');  

能找到具体单元格,所有问题也就迎刃而解了,我们甚至可以做出跟精细的排版,比如说根据列值定义跟具体的样式,大于10的左对齐,小于10的右对齐等等,都很容易实现。

效果演示:

http://www.easyui.info/easyui/demo/datagrid/062.html

原文地址:https://www.cnblogs.com/zkwarrior/p/4830721.html