持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第9天,点击查看活动详情
相信大家在开发中可能遇到过这样的场景,在表格中展示多张图片的缩略图,有时也要查看原图。直接在当前页面弹出原图是用户体验最好的。
1、table中展示多张图片
1.1、定义table
<table class="layui-table" id="currentTableId" lay-filter="currentTableFilter"></table>
table.render({
elem: '#currentTableId',
url: '',//数据来源
toolbar: '#toolbarDemo',//操作栏
defaultToolbar: [],
cols: [[
{type: 'checkbox', width: 50},//多选框
{title: '操作', minWidth: 150, toolbar: '#currentTableBar', align: 'center'},
{field: 'username', width: 80, title: '姓名', align: 'center'},
{field: 'id_card', width: 180, title: '证件号', align: 'center' },
{field: 'cert_pics', width: 250, title: '证件照', align: 'center', height:100, templet:'#showCertPics'},//图片展示使用laytpl模板
}
]],
page: true,//开启分页
skin: 'line'
});
1.2、 图片展示模板
这里我是用英文逗号区分多张图片的,一定要注意无图片时得处理。laytpl的语法初看起来比较绕,特别注意在JS代码和渲染的html代码之间要加上分隔符+#。
<script id="showCertPics" type="text/html">
{{# let certPics = d.identity_cert_pics || "";
let certPicsArr = certPics.split(",");
for(var j in certPicsArr) { certPicsArr[j] }} //循环展示图片
<div style="margin:0 10px; display:inline-block !important; display:inline; max-70px; max-height:50px; " >
<img style=" max-70px; max-height:50px;" src="{{certPicsArr[j]}}" onclick="showImg(this)" />
</div>
{{# } }}
</script>
1.3、展示效果
2、弹出层展示大图
本身layer是支持弹出层展示大图的,同时传入CSS选择器,来弹出展示对应容器内的图片的。
比如:
<div id="layer-photos-demo" class="layer-photos-demo">
<img src="缩略图" alt="图片名">
<img src="缩略图" alt="图片名">
</div>
<script>
layer.photos({
photos: '#layer-photos-demo'
});
</script>
表格中的图片layer也是支持弹出层展示的,但是必须保证每一行的数据都有图片,否则图片展示过程中就会报错。因为会弹出展示表格内的所有图片。这显然不太符合需求。
- 下面我们通过自行组装数据,来实现:
window.showImg = function (img) {
//img为this对象,即当前点击的图片容器
let showImgArr = [];
//找到img对象的祖父节点,然后找到所有的img对象
$(img.parentNode.parentNode).find('img').each(function(e) {
//遍历img对象,组装图片数据
showImgArr.push({
"alt": "",
"pid": e, //图片id
"src": this.src, //原图地址
"thumb": "" //缩略图地址
});
});
if (showImgArr) {
let shouImgObj = {
"title": "", //相册标题
"id": Math.round(Math.random()*100), //相册id
"start": 0, //初始显示的图片序号,默认0
"data": showImgArr
};
layer.photos({
photos: shouImgObj
});
}
};
- 展示效果:
展示效果还是不错的,可以左右切换图片,主要还是开发起来很快,成本低。