考虑以下(非常感谢 Creating a table linked to a csv file ):
var dataAsCsv = `Col1,Col2
Type1,"123,456"
Type2,"789,012"
Type3,"34,567"`;
var data = d3.csvParse(dataAsCsv);
var columns = ['Col1', 'Col2'];
var table = d3.select("#currentMonthTable").append("table"),
thead = table.append("thead"),
tbody = table.append("tbody");
// append the header row
thead.append("tr")
.selectAll("th")
.data(columns)
.enter()
.append("th")
.text(function(column) { return column; });
var rows = tbody.selectAll("tr")
// create a row for each object in the data
.data(data)
.enter()
.append("tr");
// create a cell in each row for each column
var cells = rows.selectAll("td")
.data(function(row) {
return columns.map(function(column) {
return {column: column, value: row[column]};
});
})
.enter()
.append("td")
.text(function(d) { return d.value; });
<script src="https://d3js.org/d3.v4.js"></script>
<body>
<div id="currentMonthTable"></div>
</body>
我想右对齐所有带有数字的单元格,并保持所有其他单元格的对齐方式相同。即:123,456
、789,012
和 34,567
都应右对齐,但所有其他对齐方式应保持不变。
在 D3 中执行此操作的最简单方法是什么?请注意,我想将此保留到 D3,以便保持能够使用 csv
数据。
直觉上,我认为正确的解决方案可能需要为所有带有数字的单元格提供一个 CSS 类,然后设置 text-align:right;
,但我不确定如何使用D3.
最佳答案
这是实现此目的的一种方法:使用 RegEx 确定字符串是否为数字
我已经使用 this answer 来检查并相应地添加了一个类:
.attr('class', function(d) {
return /^[0-9,.]*$/.test(d.value) ? 'integer' : null;
});
和 CSS:
#currentMonthTable table td.integer {
text-align: right;
}
这是一个代码片段:
var dataAsCsv = `Col1,Col2
Type1,"123,456"
Type2,"789,012"
Type3,"34,567"`;
var data = d3.csvParse(dataAsCsv);
var columns = ['Col1', 'Col2'];
var table = d3.select("#currentMonthTable").append("table"),
thead = table.append("thead"),
tbody = table.append("tbody");
// append the header row
thead.append("tr")
.selectAll("th")
.data(columns)
.enter()
.append("th")
.text(function(column) { return column; });
var rows = tbody.selectAll("tr")
// create a row for each object in the data
.data(data)
.enter()
.append("tr");
// create a cell in each row for each column
var cells = rows.selectAll("td")
.data(function(row) {
return columns.map(function(column) {
return {column: column, value: row[column]};
});
})
.enter()
.append("td")
.text(function(d) { return d.value; })
.attr('class', function(d) {
return /^[0-9,.]*$/.test(d.value) ? 'integer' : null;
});
#currentMonthTable table td.integer {
text-align: right;
}
<script src="https://d3js.org/d3.v4.js"></script>
<body>
<div id="currentMonthTable"></div>
</body>
希望对您有所帮助。
关于javascript - 右对齐在 D3 中创建的 HTML 表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48383607/