在使用border-collapse时,如何在JavaScript中计算border-bottom-width

When using border-collapse, how to compute border-bottom-width in JavaScript?

本文关键字:JavaScript 计算 border-bottom-width border-collapse      更新时间:2023-09-26

table { border-collapse: collapse; }th { border-bottom: 11px solid black }结合使用时,在JavaScript中似乎无法计算border-bottom-width

window.getComputedStyle(th).getPropertyValue('border-bottom-width')根本不起作用。看看这个小提琴在不同的浏览器中记录到控制台的内容…

  • Chrome: 11px
  • ie11: 5.5px
  • Firefox: 6px

如果我删除border-collapse,所有浏览器返回11px,正如我所期望的。

使用border-collapse时,是否有更可靠的方法来获得精确的边框宽度?或者有一种方法可以获得thead, trth的高度(包括边界),而不会遇到浏览器之间相同的不一致?

有趣!这似乎是浏览器之间的不一致,不认为有一个简单的解决方案。无论如何,这里有一个hack的解决方案/变通方法:

var th = document.getElementById('th');
var table = document.getElementById('table');
var style = window.getComputedStyle(th);
table.style.borderCollapse = 'separate';
var borderHeight = style.getPropertyValue('border-bottom-width');
table.style.borderCollapse = 'collapse';
console.log(borderHeight);
table {
  border-collapse: collapse;
}
th {
  border-bottom: 11px solid red;
}
<table id="table">
  <tr>
    <th id="th">TH</th>
  </tr>
</table>

Chrome &Firefox,都返回11px


编辑:根据@Eric N的回答,你可能会幸运地将display: block添加到th s中。这会破坏表格布局,你需要解决这个问题。示例:

var th = document.getElementById('th');
var style = window.getComputedStyle(th);
var borderHeight = style.getPropertyValue('border-bottom-width');
console.log(borderHeight);
table {
  border-collapse: collapse;
}
th {
  display: block;
  float: left;
  border-bottom: 11px solid red;
}
<table id="table">
  <tr>
    <th id="th">TH</th>
    <th>TH</th>
    <th>TH</th>
  </tr>
</table>

根据这篇文章,它似乎有一个display:table-cell(为您的单元格继承)产生不同的高度/边框宽度结果在不同的浏览器。他们建议将显示更改为block,以强制浏览器按照您的期望计算该值