代码之家  ›  专栏  ›  技术社区  ›  Rudey Mike M.

使用边框折叠时,如何在JavaScript中计算边框底部宽度?

  •  3
  • Rudey Mike M.  · 技术社区  · 10 年前

    使用时 table { border-collapse: collapse; } 与…结合 th { border-bottom: 11px solid black }

    window.getComputedStyle(th).getPropertyValue('border-bottom-width') 这根本无济于事。看看是什么 this fiddle 在不同浏览器中登录到控制台。。。

    • 铬: 11px
    • IE11: 5.5px
    • 火狐: 6px

    如果我删除 border-collapse 11px

    使用时,是否有更可靠的方法获得精确的边框宽度 边界坍塌 ? 或者,是否有一种方法可以获得 thead , tr 或 th 而不会在浏览器之间遇到同样的不一致?

    2 回复  |  直到 10 年前
        1
  •  4
  •   Community Mohan Dere    9 年前

    有趣的好像是 plain inconsistency between browsers ,不要认为有一个简单的解决方案。无论如何,这里有一个黑客解决方案/解决方法:

    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>
        2
  •  1
  •   Community Mohan Dere    9 年前

    this post ,它似乎有一个显示:表单元格(为单元格继承)在不同浏览器中产生不同的高度/边框宽度结果。他们建议将th上的显示更改为块,以强制浏览器按预期计算该值。