You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 21:01:55