使用colspan创建新的表行会更改IE中的单元格大小

时间:2012-09-11 14:25:47

标签: javascript jquery html-table

我正在研究一个相当复杂的问题,并试图将我的问题简化为一个简短的代码示例。

当我使用jQuery在表中创建新的<tr>并将colspan设置为total-number-of-columns时,表格单元格的宽度(在代码中未设置)会发生变化。这种情况发生在IE9中,但不发生在Chrome中。我知道我可以在代码中明确地给出单元格大小,但在我使用的解决方案中我无法真正做到这一点。

以下是代码:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js" type="text/javascript" ></script>

<script type="text/javascript">
    var expanded = false;
    var $detailsRow;
    $(document).ready(function(){
        //toggle the details row
        $(".selectable-row").click(function(){
            if(expanded){
                $detailsRow.remove();
                expanded = false;
            }else{
                $detailsRow = $("<tr class=\"child-row\"><td colspan=\"4\">");
                $detailsRow.find("td").text("Hellohellohellohellohellohello Hellohellohellohellohellohello Hellohellohellohellohellohello Hellohellohellohellohellohello Hellohellohellohellohellohello Hellohellohellohellohellohello Hellohellohellohellohellohello Hellohellohellohellohellohello Hellohellohellohellohellohello");
                $detailsRow.insertAfter($(this));
                expanded = true;
            }
        });
    });
</script>

<div style="width:1000px">
    <table border="1" style="width:100%">
        <tr class="selectable-row">
            <td>2012-09-03 11:33</td>
            <td>This is the 2nd column</td>
            <td>The 3rd column</td>
            <td>The last one</td>
        </tr>
    </table>
</div>

Note that it's a subtle difference, the second one is expanded, and the date-cell is slightly smaller 请注意,这是一个细微的差别,第二个是扩展的,日期单元格略小。

有人可以解释为什么会发生这种情况,是否有修复?也许以某种方式用div包裹细胞内部。我尽力了。

2 个答案:

答案 0 :(得分:1)

您所看到的是pixel-rounding errorHere另一个链接谈论它。

如果你把你的代码发布到js小提琴中,你会得到你所说的div宽度为1000但不是1001,也不是1002的错误,但是再次为1003,1004,而不是1005 .. 。 如果您将列号更改为3,则Chrome还会显示1001,1002的错误。

我不确定在添加col-span时如何重新计算表列宽度,这会导致第一个位置的移位,因为表的尺寸本身不会改变。

和K.K.提到,设置宽度:25%也为我解决了这个问题。

答案 1 :(得分:0)

你是否应用任何css来控制单元格宽度?,因为在单元格上添加css属性后,它会停止变小/变大。

<style type="text/css">
    .selectable-row td { width: 25%; }
</style>
相关问题