---
title: "数据表格JqGrid自适应列宽度"
author: "hesai_vip"
date: "2013-02-22T12:29:57Z"
tags: []
slug: "jqgrid"
draft: false
lastmod: "2013-02-22T12:32:01Z"
id: 1812381
url: "https://vipshow.iteye.com/blog/1812381"
---

**jqgrid 是一个比较好的前端数据表格，可是因为没有很详细的API，导致有时候不知所以然。**

 

        **目的：**自动显示完jqgrid中每一列的内容，而不是隐藏起来。没找到jqgrid提供的自适应列宽度的方法，只好参考了下jqgrid最终生成的DOM结构，直接用jquery操作DOM结构实现自适应列宽度功能。

 

　　**实现方法：**用一个新的表格，样式继承自jqgrid的样式，用来计算数据源中每一列的实际宽度，然后设置标头和内容表格中用来控制宽度的单元格。

 

 　　**备注：**jqgrid版本为jqGrid  4.4.1，如果使用其他版本的jqgrid，可能DOM结构不一样，需要参考最终的DOM结构来修改部分代码。

 

　　ｂｕｇ：当使用jqgrid的页头拖拽实现列宽修改时，出现的拖拽线和单元格不一致。

**jqgrid自适应列宽度修改前后效果对比**

**前：**  
**![](http://dl.iteye.com/upload/attachment/0080/7339/7a8d2aab-8f5a-31c7-ba8a-e526ebac05fc.png)**

**后：**  
**![](http://dl.iteye.com/upload/attachment/0080/7341/7a087c0c-dd90-331d-97fe-b61f1d3600fe.png)**  
 

**源代码如下**

```
<html>
<head>
<link href="css/ui.jqgrid.css" rel="stylesheet" type="text/css" />
<link href="css/jquery-ui-1.8.2.custom.css" rel="stylesheet" type="text/css" />
<script src="js/jquery.js" type="text/javascript"> </script>
<script src="js/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="js/jquery.jqGrid.min.js" type="text/javascript"> </script>
</head>
<body><!-----用来计算单元格内容实际长度的--------->
<div class="ui-jqgrid ui-widget ui-widget-content ui-corner-all" style="position:absolute;top:-9999px"><div class="ui-jqgrid-view">
<div class="ui-jqgrid-bdiv"><div style="position: relative;"><table cellspacing="0" cellpadding="0" border="0"><tr class="ui-widget-content jqgrow ui-row-ltr" style="table-layout:table"><td id="tdCompute" style="background:#eee;width:auto"></td></tr></table></div></div></div></div>
<!-----用来计算单元格内容实际长度的--------->
<table id="grid"></table>
<div id="pager"></div>
<input type="button" value="刷新" onclick='jQuery("#grid").trigger("reloadGrid");' />

<script type="text/javascript">
     $(function () {
         jQuery("#grid").jqGrid({
             datastr: '{"pageNo":1,"pageSize":4,"list":[{"id":"1","name":"selina","age":"女","q":"418114362"},{"id":"2","name":"jqGrid没有好的中文帮助需要。。。","age":"女","q":"418114362"},{"id":"3","name":"test托尔斯泰","age":"女","q":"418114362"}],"totalCount":8,"totalPage":2,"success":true}',
             datatype: "jsonstring",
             viewrecords: true,
             jsonReader: {
                 repeatitems: false,
                 total: "lastPageNo",
                 page: "pageNo",
                 records: "totalCount",
                 root: "list"
             },
             gridComplete:function(){doResize()},
             prmNames: {
                 page: "pageNo",    // 表示请求页码的参数名称  
                 rows: "pageSize",    // 表示请求行数的参数名称  
                 sort: "sort", // 表示用于排序的列名的参数名称  
                 order: "dir" // 表示采用的排序方式的参数名称  
             },
             height:200,
             colModel: [
                   { name: 'id', index: 'id'},
                   { name: 'name', index: 'name'},
                   { name: 'age', index: 'age' },
				   { name: 'q', index: 'q' }
               ],
             rowNum: 10,
             rowList: [10, 20, 30],
             caption: "jqgrid自适应宽度"
         });
     }); 
     function doResize(){
       var td=$('#tdCompute')//获取计算实际列长度的容器
           ,tds//临时保存列
           ,arr=[];//用于保存最大的列宽
        //遍历每行获得每行中的最大列宽
       $('#gview_grid .ui-jqgrid-htable tr,#grid tr:gt(0)').each(function(){
          $(this).find('td,th').each(function(idx){
            arr[idx]=Math.max(arr[idx]?arr[idx]:0,td.html($(this).text())[0].offsetWidth);
          })         
       });
       $('#gview_grid th').each(function(idx){this.style.width=arr[idx]+'px'});//设置页头单元格宽度       
       $('#grid tr:eq(0) td').each(function(idx){this.style.width=arr[idx]+'px'});//设置内容表格中控制单元格宽度的单元格，在第一行
       
       var total=$('#grid').closest('.ui-jqgrid-bdiv')[0].scrollWidth;//获取表格宽度
       $('#grid,#gview_grid .ui-jqgrid-htable').css({width:total});//设置表头表格和内容表格宽度
       $('#gbox_grid,#gview_grid,#gview_grid>div:gt(0)').css({width:total+15});//设置表头表格和内容表格父容器的宽度
     }
 </script>
</body>
</html>
```

   
 

 提供该文章的附件！