HTML에서 소수점 정렬
한 열에 십진수가 포함 된 테이블이 있습니다. 워드 프로세서의 "소수점 탭"기능과 유사한 방식으로 정렬하여 모든 점이 수직선에 놓 이도록하려고합니다.
현재 두 가지 가능한 해결책이 있지만 더 나은 것을 기대하고 있습니다 ...
해결 방법 1 : HTML 내에서 숫자 분할, 예 :
<td><div>1234</div><div class='dp'>.5</div></td>
와
.dp { width: 3em; }
(예,이 솔루션은있는 그대로 작동하지 않습니다. 그러나 개념은 유효합니다.)
해결 방법 2 : 다음에 대한 언급을 찾았습니다.
<col align="char" char=".">
이것은 참조 페이지에 따르면 HTML4의 일부이지만 내가 손에 넣어야하는 브라우저 인 FF3.5, Safari 4 또는 IE7에서는 작동하지 않습니다. 또한 숫자 형식을 CSS로 가져올 수 없다는 문제도 있습니다 (하지만 전체 열에 영향을 미치기 때문에 그렇게 놀라운 것은 아닙니다).
따라서 누구에게 더 나은 아이디어가 있습니까?
옵션과이를 달성하는 방법 은 Krijn Hoetmer의이 기사를 참조하십시오 . 이 솔루션의 핵심은 CSS와 JS를 사용하여이를 달성하는 것입니다.
(function() {
var currencies = /(\$|€|€)/;
var leftWidth = 0, rightWidth = 0;
for(var tableCounter = 0, tables = document.getElementsByTagName("table");
tableCounter < tables.length; tableCounter++) {
if(tables[tableCounter].className.indexOf("fix-align-char") != -1) {
var fCols = [], leftPart, rightPart, parts;
for(var i = 0, cols = tables[tableCounter].getElementsByTagName("col"); i < cols.length; i++) {
if(cols[i].getAttribute("char")) {
fCols[i] = cols[i].getAttribute("char");
}
}
for(var i = 0, trs = tables[tableCounter].rows; i < trs.length; i++) {
for(var j = 0, tds = trs[i].getElementsByTagName("td"); j < tds.length; j++) {
if(fCols[j]) {
if(tds[j].innerHTML.indexOf(fCols[j]) != -1) {
parts = tds[j].innerHTML.split(fCols[j]);
leftPart = parts.slice(0, parts.length -1).join(fCols[j]);
leftPart = leftPart.replace(currencies, "<span class='currency'>$1</span>");
rightPart = fCols[j] + parts.pop();
tds[j].innerHTML = "<span class='left'>" + leftPart + "</span><span class='right'>" + rightPart + "</span>";
} else {
tds[j].innerHTML = tds[j].innerHTML.replace(currencies, "<span class='currency'>$1</span>");
tds[j].innerHTML = "<span class='left'>" + tds[j].innerHTML + "</span>";
}
tds[j].className = "char-align";
var txt = document.createTextNode(tds[j].firstChild.offsetWidth);
if(leftWidth < tds[j].firstChild.offsetWidth) {
leftWidth = tds[j].firstChild.offsetWidth;
}
if(tds[j].childNodes[1]) {
txt = document.createTextNode(tds[j].childNodes[1].offsetWidth);
if(rightWidth < tds[j].childNodes[1].offsetWidth) {
rightWidth = tds[j].childNodes[1].offsetWidth;
}
}
}
}
}
}
}
// This is ugly and should be improved (amongst other parts of the code ;)
var styleText = "\n" +
"<style type='text/css'>\n" +
" .fix-align-char td.char-align { width: " + (leftWidth + rightWidth) + "px; }\n" +
" .fix-align-char span.left { float: left; text-align: right; width: " + leftWidth + "px; }\n" +
" .fix-align-char span.currency { text-align: left; float: left; }\n" +
" .fix-align-char span.right { float: right; text-align: left; width: " + rightWidth + "px; }\n" +
"</style>\n";
document.body.innerHTML += styleText;
})();
table {
border-collapse: collapse;
width: 600px;
}
th {
padding: .5em;
background: #eee;
text-align: left;
}
td {
padding: .5em;
}
#only-css td.char-align {
width: 7em;
}
#only-css span.left {
float: left;
width: 4em;
text-align: right;
}
#only-css span.currency {
float: left;
width: 2em;
text-align: left;
}
#only-css span.right {
float: right;
width: 3em;
text-align: left;
}
<table id="only-css">
<thead>
<tr>
<th>Number</th>
<th>Description</th>
<th>Costs</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Lorem ipsum dolor sit amet</td>
<td class="char-align">
<span class="left">
<span class="currency">$</span>3
</span>
<span class="right">,99</span>
</td>
</tr>
<tr>
<td>2</td>
<td>Consectetuer adipiscing elit</td>
<td class="char-align">
<span class="left">
<span class="currency">$</span>13
</span>
<span class="right">,95</span>
</td>
</tr>
<tr>
<td>3</td>
<td>Pellentesque fringilla nisl ac mi</td>
<td class="char-align">
<span class="left">
<span class="currency">$</span>4
</span>
<span class="right"></span>
</td>
</tr>
<tr>
<td>4</td>
<td>Aenean egestas gravida magna</td>
<td class="char-align">
<span class="left">
<span class="currency">$</span>123
</span>
<span class="right">,999</span>
</td>
</tr>
</tbody>
</table>
숫자 형식을 지정하는 또 다른 방법은 다음과 같습니다 35<span style="visibility: hidden">.000</span>
.. 즉, 전체 십진수 확장으로 작성하되 후행 소수점은 보이지 않는 잉크로 작성하십시오. 이렇게하면 소수점 너비에 대해 걱정할 필요가 없습니다.
사기; 이 솔루션의 이점 : 비례 글꼴에도 적용됩니다. 하나의 추가 열을 가지고 소수 구분 기호와 소수에서 정수 부분을 나눕니다. 그런 다음이 CSS를 사용하고 헤더 행에서 두 열을 결합합니다.
table {border-collapse:collapse;}
td {padding:0px;margin:0px;border:0px;}
td+td {text-align:right;}
td, td+td+td {text-align:left;}
<table>
<tr><th>Name</th><th colspan=2>Height</th></tr>
<tr><td>eiffeltower</td> <td>324</td> <td></td></tr>
<tr><td>giraffe</td> <td>5</td> <td>,30</td></tr>
<tr><td>deer</td> <td>1</td> <td></td></tr>
<tr><td>mouse</td> <td>0</td> <td>,03</td></tr>
</table>
나는 jQuery를 가지고 놀았고 이것을 생각 해냈다.
$(document).ready(function() {
$('.aBDP').each(function() {
var wholePart, fractionPart;
wholePart = Math.floor($(this).text()-0);
fractionPart = Math.floor(($(this).text() % 1)*10000 + 0.5) / 10000 + "";
html = '<span class="left">' + wholePart + '.' + '</span>';
html += '<span class="right">' + fractionPart.substring(2) + '</span>';
$(this).html(html);
})
})
.right {
text-align: left;
}
.left {
float:left;
text-align: right;
width:10em;
}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js" type="text/javascript"></script>
<table width="600" border="1">
<tr><th></th><th>Aligned Column</th></tr>
<tr><th>1st Row</th><td class='aBDP'>1.1</td></tr>
<tr><th>2nd Row</th><td class='aBDP'>10.01</td></tr>
<tr><th>3rd Row</th><td class='aBDP'>100.001</td></tr>
<tr><th>4th Row</th><td class='aBDP'>1000.0001</td></tr>
</table>
작동하는 것 같았습니다.
숫자를 인쇄하여 항상 소수점 이하 자릿수를 유지하고 올바르게 정렬 할 수 있습니까?
긴 답변도 중요하지만 짧은 답변을 좋아해서 좋아했습니다.
35<span style="color:transparent">.000</span>
추가하고 싶습니다.
<TD><div style='float:right;'><?php echo number_format($totalAmount,2); ?></div></TD>
PHP를 믹스에 던지십시오. 고정 너비 글꼴에 많이 의존하지만 후자는 나를 위해 작동합니다. 데이터는 이미 표 형식이므로 셀 내에 다른 표를 추가하는 것은 입력이 너무 많고 유지 관리가 어렵습니다.
수천년 전에 (또는 2-3 년) 여전히 작동하는 것처럼 보이는 align = "char"를 에뮬레이트하는 jQuery shim을 작성했습니다. 그것은 CSS 패딩을 사용하고 colspans에 대한 계정을 사용하므로 적당히 영리하지만 실제로는 예쁜 코드가 아닙니다 (그 당시에는 자바 스크립트로 시작했습니다). 나는 누군가가 그것을 다시 작성하기를 원합니다.
그동안 이것이 도움이되는지 확인하십시오 : https://gist.github.com/inanimatt/f27ffd25c174e9d8a0907455395d147d
퀴즈 : 브라우저가 열 스타일을 제대로 지원하지 않는 이유는 테이블이 2D 데이터 구조이고 DOM (Javascript와 CSS가 작동하는 방식, HTML5가 정의되는 방식)이 순전히 계층 적이므로 두 열을 모두 나타낼 수 없기 때문입니다. 및 행. 대신 단순히 행과 셀을 정의하고 열을 전혀 나타내지 않습니다.
숫자가 고정 폭인 경우, 소수점 앞의 자릿수에 따라 자바 스크립트를 사용하여 셀의 패딩 (ems)을 조정할 수 있습니다. 그렇지 않으면 까다로울 수 있습니다.
Krijn Hoetmer가 만든 기능은 prettyPhoto ( http://www.no-margin-for-errors.com/projects/prettyphoto-jquery-lightbox-clone/ )를 방해 하므로 jQuery 버전을 만들었습니다. 사전 정의 된 통화를 기반으로 문자열을 대체하는 대신 동적으로 만들어야하므로 통화 부분이 제거됩니다.
phpjs의 빈 함수가 필요합니다 : http://phpjs.org/functions/empty:392 .
사용 된 jQuery는 버전 1.6입니다.
/* This function will align table columns on the char if in the col from the
* colgroup has the property 'align="char"' and a attribute 'char'. The alignment
* is done on the first occurence of the specified char.
*
* The function is inspired from:
*
* http://krijnhoetmer.nl/stuff/javascript/table-align-char/
* http://stackoverflow.com/questions/1363239/aligning-decimal-points-in-html
*/
function alignNumbers()
{
var table; /* This will store the table currently working on . */
var i = 0; /* Every column can have it's own width, the counter makes the class name unique. */
/* Get all tables for which the alignment fix must be done.
*
* Note: this could even be further optimized by just looking for tables where
* there is a a col with 'align="char"'.
*/
$('table.fix-align-char').each(function(index)
{
table = $(this);
/* All table columns are fetched to have a correct index, without it it's
* hard to get the correct table cells.
*/
$(this).find('col').each(function(index)
{
/* Only those table cells are changed for which the alignment is set to
* char and a char is given.
*/
if ($(this).prop('align') == 'char' && !empty($(this).attr('char')))
{
/* Variables for storing the width for the left and right part (in pixels). */
var left_width = 0, right_width = 0;
var col, left_part, right_part, parts, new_html;
i++; /* Increase the counter since we are working on a new column. */
col = $(this);
/* For the col index + 1 (nth-child starts counting at 1), find the table
* cells in the current table.
*/
table.find('> tbody > tr > td:nth-child('+ (index + 1) +')').each(function(index)
{
/* Split the html on the specified char. */
parts = $(this).html().split(col.attr('char'));
new_html = '';
/* The first element is always the left part. The remaining part(s) are
* the right part. Should there be more chars in the string, the right
* parts are rejoined again with the specified char.
*/
left_part = parts.shift();
right_part = parts.join(',');
/* Add a left part to the new html if the left part isn't empty*/
if (!empty(left_part))
{
new_html = new_html + '<span class="left">' + left_part + '</span>';
}
/* Add the specified char and the right part to the new html if
* the right part isn't empty*/
if (!empty(right_part))
{
new_html = new_html + col.attr('char') + '<span class="right">' + right_part + '</span>';
}
/* If there is a new html, the width must be determined and a class is
* added.
*
* Note: outerWidth is used instead of width so padding, margin and
* borders are taken into account.
*/
if (!empty(new_html))
{
$(this).html(new_html); /* Set the new html. */
$(this).addClass('char-align-' + i); /* Add a class to the table cell. */
/* Get the left span to determine its outer width. */
leftSpan = $(this).children('.left');
if (!empty(leftSpan) && left_width < leftSpan.outerWidth())
{
left_width = leftSpan.outerWidth();
}
/* Get the right span to determine its outer width. */
rightSpan = $(this).children('.right');
if (!empty(rightSpan) && right_width < rightSpan.outerWidth())
{
right_width = rightSpan.outerWidth();
}
}
});
/* Only if any width is larger then 0, add a style. */
if (left_width > 0 || right_width > 0)
{
style_text = '<style type="text/css">.fix-align-char td.char-align-' + (i) + ' span.left { float: left; text-align: right; width: ' + (left_width) + 'px; }\n.fix-align-char td.char-align-' + (i) + ' span.right { float: right; text-align: left; width: ' + right_width + 'px; }</style>';
$('head').append(style_text);
}
}
});
});
}
$(document).ready(function(){
alignNumbers();
});
이 문제를 해결하기 위해 JavaScript를 사용했습니다. 이것은 제 HTML입니다.
<body>
<table id="nadis">
</tr>
</table>
</body>
이것은 내 JavaScript입니다.
var numarray = ["1.1", "12.20", "151.12", 1000.23,12451];
var highetlen = 0;
for(var i=0; i<numarray.length; i++){
var n = numarray[i].toString();
var res= n.split(".");
n = res[0];
if(highetlen < n.length){
highetlen = n.length;
}
}
for(var j=0; j<numarray.length; j++){
var s = numarray[j].toString();
var res= s.split(".");
s = res[0];
if(highetlen > s.length){
var finallevel = highetlen - s.length;
var finalhigh = "";
for(k=0;k<finallevel;k++){
finalhigh = finalhigh+ '  ';
}
numarray[j] = finalhigh + numarray[j];
}
var nadiss = document.getElementById("nadis");
nadiss.innerHTML += "<tr><td>" + numarray[j] + "</td></tr>";
}
참고 URL : https://stackoverflow.com/questions/1363239/aligning-decimal-points-in-html
'Programing' 카테고리의 다른 글
Scala에 적합한 GUI 프레임 워크? (0) | 2020.11.09 |
---|---|
PL / SQL에서 함수와 프로 시저의 차이점은 무엇입니까? (0) | 2020.11.09 |
판매 통계는 iTunes Connect에서 얼마나 자주 업데이트됩니까? (0) | 2020.11.09 |
HTML5 라이브 스트리밍 (0) | 2020.11.09 |
이론적으로 C ++ 구현이 두 함수 인수의 평가를 병렬화 할 수 있습니까? (0) | 2020.11.09 |