简体   繁体   English

如何在javascript中将列填充添加到特定表的第一列?

[英]How to add column padding to the first column of a specific table in javascript?

I have a table which is created dynamically in javascript. 我有一个在javascript中动态创建的表。

EDIT: Example code to create the table is here : 编辑:创建表的示例代码在这里

I need to add spacing between the two columns (eg 50px). 我需要在两列之间添加间距(例如50px)。 I have read that the best way is to add padding to the right of the first column, but I am not sure how to add the spacing to the first column in javascript using the table's class name? 我已经读过最好的方法是在第一列的右边添加填充,但我不知道如何使用表的类名将空格添加到javascript中的第一列?

I added the CSS provided in the original answers like so: 我添加了原始答案中提供的CSS,如下所示:

.informationWindowTable > tr > td:first-child {padding-right:50px;}

but it does not get applied to the table and that is why I asked for a solution in javascript. 但它没有应用到表中,这就是我在javascript中要求解决方案的原因。 How do I ensure that the CSS is called only after the table is created? 如何确保仅在创建表后调用CSS?

This is best done in CSS 这最好在CSS中完成

table tr td:first-child {
  padding-right: 50px;
}

However, it can be done in JavaScript 但是,它可以在JavaScript中完成

var tableCells = document.querySelectorAll("table tr td:first-child");

for (var i = 0; i < tableCells.length; i++) {
    tableCells[i].classList.add("give-padding");
}

Fiddle: http://jsfiddle.net/8y9qc0o0/ 小提琴: http//jsfiddle.net/8y9qc0o0/

Instead of adding to the classList , you can also use the document.style.property syntax. 您也可以使用document.style.property语法,而不是添加到classList

tableCells[i].style.padding-right("50px");

Depending on the usecase border-spacing property might also be useful: 根据用例border-spacing属性可能也很有用:

 .tab { border-collapse: separate; border-spacing: 50px 1px; } .tab td {border: 1px #AAA solid; padding: 10px;} 
 <table class="tab"> <tr> <td>1</td> <td>2</td> </tr> <tr> <td>3</td> <td>4</td> </tr> </table> 

You should CSS to accomplish that. 你应该用CSS来实现这一目标。 Use the :first-child selector. 使用:first-child选择器。

td:first-child { text-align: right }

Font: Set alignment and padding of first and second column in <table> via CSS 字体: 通过CSS在<table>中设置第一列和第二列的对齐和填充

Perhaps splitting the padding between the two td is the best for balance 也许在两个td之间分割填充是最好的平衡

 .tab td:nth-child(even) {padding-left:25px;} .tab td:nth-child(odd){padding-right:25px;} 
 <table class="tab"> <tr> <td>1</td> <td>2</td> </tr> <tr> <td>3</td> <td>4</td> </tr> </table> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM