国内外的网站都翻了一遍都没有找到一个通用的jqgrid能自适应列宽的方法,要么是太繁琐,要么是不能用,通过参照http://vipshow.iteye.com/blog/1812381这篇文章,自己稍作修改写了个通用的,希望能帮到那些苦苦寻觅的人。代码如下:
首先设置div样式,该样式随意放,只要能找到就行
<!-----用来计算单元格内容实际长度的--------->
<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>
<!-----用来计算单元格内容实际长度的--------->
然后js:
//重新调整jqgrid每列的宽度
function jqgridColResize(){
var td=$('#tdCompute')//获取计算实际列长度的容器
,tds//临时保存列
,arr=[];//用于保存最大的列宽
//遍历每行获得每行中的最大列宽
$('.ui-jqgrid-htable tr,.ui-jqgrid-btable 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);
})
});
$('.ui-jqgrid-labels th').each(function(idx){this.style.width=arr[idx]+'px'});//设置页头单元格宽度
$('.ui-jqgrid-btable tr:eq(0) td').each(function(idx){this.style.width=arr[idx]+'px'});//设置内容表格中控制单元格宽度的单元格,在第一行
}
使用时在gridComplete这个方法里所有的逻辑都执行完后,在最后调用jqgridColResize就行,如果你写的有表格宽度自适应还需要在那个函数里再调用一次,不然页面尺寸改变后,这个就不起作用了。使用方法如下:
效果图: