javascript 获取表格行的高度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4243350/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 10:45:34  来源:igfitidea点击:

Getting the height of a table row

javascripthtmlcssdomrow

提问by user495688

How can I calculate the height of a row (in pixels) in a table with JavaScript?

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

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

回答by Tim

function findHeights() {
            var tbl = document.getElementById('your table').rows;
            alert(tbl[0].offsetHeight); // row 1
}

回答by Jinesh Parekh

document.getElementById('your_row_id').offsetHeight;

回答by Gosi

I've done a few calculations.

我做了一些计算。

  1. Get the total height value
  2. Get the padding-topvalue
  3. Get the padding-bottomvalue
  4. Get the margin-topvalue
  5. Get the margin-bottomvalue
  6. Get the border-spacevalue
  1. 获取总高度值
  2. 获取padding-top价值
  3. 获取padding-bottom价值
  4. 获取margin-top价值
  5. 获取margin-bottom价值
  6. 获取border-space价值

Now with all these information, we can take the total heigt and minus off the paddings, margins and border-space.

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

I've commented in the code on what each line does.

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

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>

I've added that css just for you to see that it does minus of all the padding values and gives the exact height of the td.

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

Update 1: Added calculations for border-space.

更新 1:添加了border-space.

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

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

Also, as explained in the comment, window.getComputedStyle(elmnt, null).getPropertyValue('-webkit-border-vertical-spacing')gets values in pixels, so even if it is set in percentages, it will retrieve what is its pixel value.

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

So from this, we can pretty much just get the total value of height and then minus off all the paddings, margins and border-space.

所以从这里,我们几乎可以得到高度的总值,然后减去所有的填充、边距和边框空间。

回答by benvc

If you want to get an accurate table row height, then you should use Element.getBoundingClientRect()rather than Element.offsetHeightin order to get fractional height rather than a rounded figure.

如果您想获得准确的表格行高,那么您应该使用Element.getBoundingClientRect()而不是Element.offsetHeight为了获得分数高度而不是圆角数字。

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

If you also want to include border-spacingin your calculation of table row height, you need to decide how you want to allocate it to each row (since it is really space between rows and not part of any particular row). Also, be sure to check whether or not the table's border-collapseproperty is set to collapse(if so, then border-spacingis not included in your table).

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

In the snippet below, the first / last rows are allocated the space above / below that is not shared with another row, all space between rows is shared evenly. This ensures that the sum of all row heights is equal to the table height.

在下面的代码片段中,第一行/最后一行分配了不与另一行共享的上/下空间,行之间的所有空间均等共享。这确保所有行高的总和等于表格高度。

Alternatively, you could choose not to allocate the space above the first row or below the last row to any row, since this space is not included in the height calculation for <thead>or <tbody>elements so that space could be allocated to those elements rather than the rows themselves.

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

const getRowHeight = (tr) => {
  let height = tr.getBoundingClientRect().height;
  let table = tr.closest('table');
  let style = window.getComputedStyle(table);
  let collapse = style.getPropertyValue('border-collapse');
  let space = parseFloat(
    style.getPropertyValue('border-spacing').split(' ')[1].replace(/[^\d.]/g, '')
  );
  
  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;
}

// comments below are examples only (will change based on defaults, zoom, etc)

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>

回答by ankitkanojia

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>

回答by mrbear258

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>

You can probably find a better way to loop through the <tr> element.

您可能会找到一种更好的方法来循环遍历 <tr> 元素。

 

 

Simple code explanation:

简单代码说明:

Gets all the table rows from tbody and loops through all of them using nth-child.

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

It then sets the row (var row_selector) and obtains its vertical spacing, margin (top and bottom) and the offsetHeight (element height, padding, etc.).

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

Since offsetHeight only gets the padding, border and scrollbar, but not the margin, we need to get the computed style value like we did with vertical border spacing.

由于 offsetHeight 只获取填充、边框和滚动条,而没有获取边距,因此我们需要像处理垂直边框间距一样获取计算出的样式值。

Finally it parses the vertical border spacing and the margin values to an Int and adds it to offsetHeight and logs the final value to the console.

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

回答by Malik Tahir

Sorry Was messed up there a sec

抱歉,一秒钟搞砸了

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

If you need to get it, you can give the tr an ID and use getElementById().offsetHeight

如果你需要得到它,你可以给 tr 一个 ID 并使用 getElementById().offsetHeight