[{"createTime":1735734952000,"id":1,"img":"hwy_ms_500_252.jpeg","link":"https://activity.huaweicloud.com/cps.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=V1g3MDY4NTY=&utm_medium=cps&utm_campaign=201905","name":"华为云秒杀","status":9,"txt":"华为云38元秒杀","type":1,"updateTime":1735747411000,"userId":3},{"createTime":1736173885000,"id":2,"img":"txy_480_300.png","link":"https://cloud.tencent.com/act/cps/redirect?redirect=1077&cps_key=edb15096bfff75effaaa8c8bb66138bd&from=console","name":"腾讯云秒杀","status":9,"txt":"腾讯云限量秒杀","type":1,"updateTime":1736173885000,"userId":3},{"createTime":1736177492000,"id":3,"img":"aly_251_140.png","link":"https://www.aliyun.com/minisite/goods?userCode=pwp8kmv3","memo":"","name":"阿里云","status":9,"txt":"阿里云2折起","type":1,"updateTime":1736177492000,"userId":3},{"createTime":1735660800000,"id":4,"img":"vultr_560_300.png","link":"https://www.vultr.com/?ref=9603742-8H","name":"Vultr","status":9,"txt":"Vultr送$100","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":5,"img":"jdy_663_320.jpg","link":"https://3.cn/2ay1-e5t","name":"京东云","status":9,"txt":"京东云特惠专区","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":6,"img":"new_ads.png","link":"https://www.iodraw.com/ads","name":"发布广告","status":9,"txt":"发布广告","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":7,"img":"yun_910_50.png","link":"https://activity.huaweicloud.com/discount_area_v5/index.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=aXhpYW95YW5nOA===&utm_medium=cps&utm_campaign=201905","name":"底部","status":9,"txt":"高性能云服务器2折起","type":2,"updateTime":1735660800000,"userId":3}]
开源框架Pear Admin,LayUI版本2.7.0.rc-5。
layui的table组件-基础参数-cellMinWidth可以设置最小宽度,表头参数可以设置width,以上可以适用大部分表格展示。
如今遇到一个需求,需要表格内容自适应,由单元格撑开宽度,找了api没有发现实现参数。
度娘未果,以下代码是自己实现的,如有问题请指正。
注意:字段较少时,请不要这样使用,直接设置宽度,不然表格内容会塌陷。
逻辑简单粗暴,关键参数(不是layui指定的参数,但是可以识别,layui指定设置数字和百分比)
cellMinWidth: 'auto'
然后根据表格内容宽度设置表头宽度(layui数据和表头是两个‘table’)。
1. html页面
<table id="topic-table" lay-filter="topic-table"></table>
2. js代码
// 字段内容省略 var cols = [{}]; // 表格渲染 table.render({ elem: '#topic-table', url:
ctx + 'topic/table', loading: true, height: 'full-65', page: true, cols: cols,
skin: 'row,line', even: true, cellMinWidth: 'auto', toolbar: '#topic-toolbar',
defaultToolbar: [{ title: '刷新', layEvent: 'refresh', icon: 'layui-icon-refresh'
}], done: function (res, curr, count) { var $data =
$('div[lay-id="topic-table"]').find('.layui-table-body').find('tr').eq(0).find('td');
var $head =
$('div[lay-id="topic-table"]').find('.layui-table-header').find('tr').eq(0).find('th');
for (var i = 0; i < $data.length; i++) { var l1 =
$data.eq(i).find('div').width(); var l2 = $head.eq(i).find('div').width(); if
(l1 > l2) { $head.eq(i).find('div').width(l1); } else {
$data.eq(i).find('div').width(l2); } } } });
3. 实现效果