HTML表格单元格居中问题:单个签名需居中,双签名保持现状
解决方案
要实现单行仅有单个签名时占满整行居中,两个签名时各占50%的效果,只需要在生成单元格时,判断当前元素是否是最后一个且总元素数为奇数,如果是则将单元格宽度设为100%,否则保持50%即可。
修改后的完整代码如下:
var result = [ {name: "John", jobPosition: "President"}, {name: "Marc", jobPosition: "Director"}, {name: "Paul", jobPosition: "Director"}, {name: "Mary", jobPosition: "Director"}, {name: "Carl", jobPosition: "Geral Secretary"}, ]; var table = '<table style=" height: 94px;" border="0" width="100%" cellspacing="0" cellpadding="0"><tbody>'; result.forEach(function(item, index) { if (index % 2 == 0) { table += '<tr style="height: 35px;">'; } // 判断是否是最后一个元素且总数量为奇数 var tdWidth = (index === result.length - 1 && result.length % 2 !== 0) ? '100%' : '50%'; table += '<td style="width: ' + tdWidth + '; height: 150px; text-align: center; font-family: arial; font-size: 12pt;" valign="top"><p>_____________________________</p><p>' + item.name + '</p><p>' + item.jobPosition + '</p></td>'; if (index % 2 == 1 || index == (result.length - 1)) { table += '</tr>'; } }); table += '</tbody></table>'; gs.info(table);
关键修改说明
- 新增
tdWidth变量,通过index === result.length - 1 && result.length % 2 !== 0判断是否需要将单元格宽度设为100%:index === result.length - 1:当前元素是数组最后一个result.length % 2 !== 0:数组总元素数为奇数(意味着最后一行只有一个元素)
- 将原固定的
width: 50%替换为动态计算的tdWidth,实现单个签名占满整行的效果
内容的提问来源于stack exchange,提问作者Flávio Tiezzi
相关产品推荐
相关产品推荐

