我正在使用jQuery对td
标签进行一些操作 - 我将它们的宽度设置为与另一个表中td
的宽度相同(实际上这是一个固定标头 - 表插件,所以我必须使用表 - 一个用于标题,一个用于主要内容。相应的th
和td
应该具有相同的宽度。)
如果我在Chrome中查看“计算风格”,所有计算器都能正常工作 - 宽度设置正确 但是,实际宽度不同于“计算宽度”!
查看td
元素计算样式的图片:
现在你可能会认为元素的实际宽度是 1 + 1 + 96 + 1 + 1 = 100 ,但它是99!
我发现了这个问题 - Computed column width is different than css declared width for column. How does browser decide width?并遵循我使用的建议table-layout: fixed;
。我也使用border-collapse: collapse;
来删除列之间的空格,所以我不认为这会是问题所在。
以下是我的代码的一部分,它设置了td width
s:
$('thead th, tbody tr:first td').each(function(i, el){
i %= col_count; // I'm using because we go through 2 lines.
// It shows at which td we are. */
// col_width is an array with already calculated
// widths (using .outerWidth()) for each column */
// if the needed width is the same as the current td's,
// we can go to the next td */
if(col_width[i] == $(this).outerWidth()) return 1;
// the width to be set with substracted borders and paddings
// (here we don't have margins)
var new_width = col_width[i] - ($(this).outerWidth() - $(this).width());
$(this).width(new_width);
// I have also tried this, but the result was the same:
// $(this).css('width', new_width + 'px');
});
我应该注意到thead th
和tbody td
来自不同的表格(正如我之前提到的)
我尝试了另一件事 - 为每列添加一个像素 - $(this).width(new_width + 1);
。在演示页面上它有效。我将新代码复制到真实页面以及几乎所有表格上都有效!只有一张表存在问题。
它证明了容器(表所在的位置)不够宽,因此滚动条“使”列更短。当然,我扩大了容器的宽度。问题消失了。
在问(写)这个长问题时,我解决了它!所以现在它正在改变一点:为什么?
为什么当我添加一个额外的像素时,问题就消失了?为什么computed width
与real width
不同?
当然,如果你为我提供另一种更专业的解决方案,我会很高兴的。)
JSFIDDLE(已设置宽度,从chrome控制台复制)。调整result
框的大小以正确查看整个表格。
答案 0 :(得分:2)
计算宽度和实际宽度的差异是由于使用了border-collapse:collapse。
border-collapse:collapse
尽可能将边框折叠为单个边框(将忽略边框间距和空单元格属性)
每个td元素的宽度减少1px,因为每个元素的边框都缩小为单边框。
答案 1 :(得分:0)
计算宽度与实际宽度不同,因为每个元素左右都有1px边框和1 px白色空间,与顶部和底部相同。