【问题标题】:Getting the height of a table row获取表格行的高度
【发布时间】:2011-05-13 16:51:33
【问题描述】:

如何使用 JavaScript 计算表格中行的高度(以像素为单位)?

<table>
  <tr>
    <td>Cell 1</td>
    <td>Cell 2</td>
  </tr>
</table>

【问题讨论】:

  • 注意:这不像clientHeightoffsetHeightscrollHeight那么简单。桌子上的边框间距开始发挥作用。 jsfiddle.net/xbtp1je8
  • @Brad 为什么要包括边框间距?从技术上讲,它不计入tr 的高度。这是两个tr之间的空白区域
  • @TemaniAfif 我的目标是确定行的有效高度,以便在具有数千行、大量单元格的虚拟网格中使用。一次在 DOM 中放入数千行并不快。因此,我使用了一种技术,其中仅显示滚动窗格中可见的行(以及它们周围的一些行)。这需要知道行的确切像素高度,包括边框间距。否则,滚动会关闭一点。
  • @TemaniAfif 我已经尝试过了,这在大多数情况下都有效,但在放大/缩小时似乎有点中断。 2px 不知何故变成了 1.75px。 (而且,这没有明确的 border-spacing 规则集......只是默认样式表。)
  • @Brad - 我认为缩放问题与使用 offsetHeight 作为基本测量值有关,因为它返回一个四舍五入的数字。您可以使用getBoundingClientRect().height 返回分数高度并避免缩放问题(我认为)。

标签: javascript html css dom row


【解决方案1】:

如果表格可以滚动..并且滚动需要高度

<div id="scrolling_chat" style="height:500px;overflow-y:auto;overflow-x: visible;">

 <table id = "chat" ></table>
           

 height = $("#scrolling_chat")[0].scrollHeight/document.getElementById("chat").rows.length;

据我所知,最准确...

【讨论】:

    【解决方案2】:

    如果您想获得准确的表格行高,那么您应该使用Element.getBoundingClientRect() 而不是Element.offsetHeight 以获得分数高度而不是四舍五入的数字。

    document.querySelector('tr').getBoundingClientRect().height;
    

    如果您还想在计算表格行高时包含border-spacing,您需要决定如何将其分配给每一行(因为它实际上是行之间的空间,而不是任何特定行的一部分)。另外,请务必检查表的border-collapse 属性是否设置为collapse(如果是,则border-spacing 不包含在您的表中)。

    在下面的sn-p中,第一行/最后一行被分配了上面/下面不与另一行共享的空间,行之间的所有空间均分。这样可以确保所有行高的总和等于表格高度。

    或者,您可以选择不将第一行上方或最后一行下方的空间分配给任何行,因为该空间不包括在 &lt;thead&gt;&lt;tbody&gt; 元素的高度计算中,因此空间可以分配给这些元素而不是行本身。

    // example log output comments below will change based on browser defaults, zoom, etc
    const getRowHeight = (tr) => {
      const table = tr.closest('table');
      const style = window.getComputedStyle(table);
      const collapse = style.getPropertyValue('border-collapse');
      const space = parseFloat(
        style.getPropertyValue('border-spacing').split(' ')[1].replace(/[^\d.]/g, '')
      );
      
      let height = tr.getBoundingClientRect().height;
      if (collapse === 'separate') {
        if (table.rows.length === 1) {
          height += space * 2;
        } else if (tr.rowIndex === 0 || tr.rowIndex === table.rows.length - 1) {
          height += space + space / 2;
        } else {
          height += space;
        }
      }
      
      return height;
    };
    
    console.log(getRowHeight(document.querySelector('#single')));
    // 24 (20px row height + 2px space above + 2px space below)
    
    console.log(getRowHeight(document.querySelector('#top')));
    // 23 (20px row height + 2px space above + 1px space below)
    
    console.log(getRowHeight(document.querySelector('#middle')));
    // 22 (20px row height + 1px space above + 1px space below)
    
    console.log(getRowHeight(document.querySelector('#bottom')));
    // 23 (20px row height + 1px space above + 2px space below)
    <table>
      <tr id="single">
        <td>Cell</td>
      </tr>
    </table>
    <table>
      <tr id="top">
        <td>Cell</td>
      </tr>
      <tr id="middle">
        <td>Cell</td>
      </tr>
      <tr id="bottom">
        <td>Cell</td>
      </tr>
    </table>

    【讨论】:

    • 这是最准确的......但它比实际多 1 个像素。
    【解决方案3】:

    对不起,一秒钟搞砸了

    <table>
      <tr onclick="alert(this.offsetHeight)">
        <td>
          Hey
          <br /> You
        </td>
      </tr>
    </table>
    

    如果需要获取,可以给tr一个ID,使用getElementById().offsetHeight

    【讨论】:

      【解决方案4】:

      我做了一些计算。

      1. 获取总高度值
      2. 获取padding-top
      3. 获取padding-bottom
      4. 获取margin-top
      5. 获取margin-bottom
      6. 获取border-space

      现在有了所有这些信息,我们可以将总高度减去填充、边距和边框空间。

      我已经在代码中注释了每一行的作用。

      var elmnt = document.getElementsByTagName("td")[0];
      var totalHeight = elmnt.offsetHeight; // gets the total height value inclusive of all paddings & margins
      
      // The following is to get the padding-top, padding-bottom, margin-top, margin-bottom values
      var paddedHeightTop = window.getComputedStyle(elmnt, null).getPropertyValue('padding-top');
      var paddedHeightBottom = window.getComputedStyle(elmnt, null).getPropertyValue('padding-bottom');
      var marginHeightTop = window.getComputedStyle(elmnt, null).getPropertyValue('margin-top');
      var marginHeightBottom = window.getComputedStyle(elmnt, null).getPropertyValue('margin-bottom');
      var borderHeight = window.getComputedStyle(elmnt, null).getPropertyValue('-webkit-border-vertical-spacing');
      
      
      // To remove the px from the string so we can use it as an integer to subtract from total value.
      var newPaddedHeightTop = paddedHeightTop.substring(0, paddedHeightTop.length - 2); // remove the px
      var newPaddedHeightBottom = paddedHeightBottom.substring(0, paddedHeightBottom.length - 2); // remove the px
      var newMarginHeightTop = marginHeightTop.substring(0, marginHeightTop.length - 2); // remove the px
      var newMarginHeightBottom = marginHeightBottom.substring(0, marginHeightBottom.length - 2); // remove the px
      var newBorderHeight = borderHeight.substring(0, marginHeightBottom.length - 2); // remove the px
      
      // Take the total and minus of all these paddings, margins and border-space
      var finalHeight = totalHeight - newPaddedHeightTop - newPaddedHeightBottom - newMarginHeightTop - newMarginHeightBottom - newBorderHeight;
      
      alert(totalHeight + " (total height) - " + newPaddedHeightTop + " (padding-top) - " + newPaddedHeightBottom +  " (padding-bottom) - " + newMarginHeightTop + " (margin-top) - " + newMarginHeightBottom + " (margin-bottom) - " + newBorderHeight + " (border-space) = "  + finalHeight);
      td {
        height: 50px;
        padding: 2px;
        border-spacing: 2px 3px;
      }
      <table>
        <tr>
          <td>Cell 1</td>
          <td>Cell 2</td>
        </tr>
      </table>
      
      <pre></pre>

      我添加了该 css 只是为了让您看到它减去了所有填充值并给出了 td 的确切高度。

      更新 1:添加了 border-space 的计算。

      var borderHeight = window.getComputedStyle(elmnt, null).getPropertyValue('-webkit-border-vertical-spacing');

      此外,正如评论中所解释的,window.getComputedStyle(elmnt, null).getPropertyValue('-webkit-border-vertical-spacing') 以像素为单位获取值,因此即使以百分比设置,它也会检索其像素值。

      因此,我们几乎可以得到高度的总值,然后减去所有的内边距、边距和边框空间。

      【讨论】:

      • 学到了新东西,能不能稍微解释一下getComputedStyle(elemnt, null),(null是干什么的)
      • @Ankit null 实际上是一个伪元素。在这种情况下,我们没有,所以我设置为空。我在w3schools.com/jsref/jsref_getcomputedstyle.asp 研究过这个。您可以将此作为参考。它是一个可选选项。
      • 这实际上并没有回答问题,因为它没有考虑边框间距。假设测量值总是以像素为单位也是危险的。
      • @Brad window.getComputedStyle(elmnt, null).getPropertyValue('padding-top'); var paddedHe 将始终返回以像素为单位的值。即使填充在% 中,它也会得到它的像素值。试试把css padding值改成5%就可以看到了。
      • @Gosi 有意思,不知道!感谢您提供信息。
      【解决方案5】:

      var table_elements = document.querySelector("table>tbody");
      var i;
      for (i = 1; i <= table_elements.rows.length; i++) {
        var row_selector = "table>tbody>tr:nth-child(" + [i] + ")";
        var table_row = document.querySelector(row_selector);
        var vertical_spacing = window.getComputedStyle(table_row).getPropertyValue("-webkit-border-vertical-spacing");
        var margin_top = window.getComputedStyle(table_row).getPropertyValue("margin-top");
        var margin_bottom = window.getComputedStyle(table_row).getPropertyValue("margin-bottom");
        var row_height= parseInt(vertical_spacing, 10)+parseInt(margin_top, 10)+parseInt(margin_bottom, 10)+table_row.offsetHeight
      
        console.log("The height is: "+row_height+"px");
      }
      <table>
        <tr>
          <td>Cell 1</td>
          <td>Cell 2</td>
        </tr>
      </table>

      您可能会找到一种更好的方法来遍历

      元素。

       

      简单代码说明:

      从 tbody 获取所有表行,并使用 nth-child 遍历所有行。

      然后设置行 (var row_selector) 并获取其垂直间距、边距(顶部和底部)和 offsetHeight(元素高度、填充等)。

      由于 offsetHeight 只获取内边距、边框和滚动条,但不获取边距,我们需要像处理垂直边框间距一样获取计算出的样式值。

      最后,它将垂直边框间距和边距值解析为 Int 并将其添加到 offsetHeight 并将最终值记录到控制台。

      【讨论】:

        【解决方案6】:

        var tableHeight =  document.getElementById("tableId").offsetHeight;
        var totalRowInTable =  document.getElementById("tableId").rows.length;
        
        //So here we have total height of table and total <tr> tags, so tableHeight / total <tr> tag will gave each <tr> tag height.
        var trTagHeight = tableHeight/totalRowInTable;
        console.log(trTagHeight);
        
        //Note: This is approx value of each row, excluding padding and cell padding value.
        <table id="tableId">
          <tr>
            <td>Cell 1</td>
            <td>Cell 2</td>
          </tr>
          <tr>
            <td>Cell 1</td>
            <td>Cell 2</td>
          </tr>
        </table>

        【讨论】:

        • 这可能是迄今为止最接近的答案。唯一的问题是它不能保证任何特定的行......只是所有这些行的平均高度。如果所有行的高度相同,这可能无关紧要。
        • 而且也有可能超出高度,不是吗?那么我们如何根据行数来计算呢?
        【解决方案7】:
        document.getElementById('your_row_id').offsetHeight;
        

        【讨论】:

        • offsetheight是否也适用于确定段落的行高?
        【解决方案8】:
        function findHeights() {
                    var tbl = document.getElementById('your table').rows;
                    alert(tbl[0].offsetHeight); // row 1
        }
        

        【讨论】:

        • 你还需要知道'border-spacing'。
        猜你喜欢
        • 2016-01-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-28
        • 2012-10-06
        相关资源
        最近更新 更多