我希望表格自动将单元格对齐为每行两个,这意味着如果添加/删除单元格,单元格将变为每行两个(如果单元格总数为奇数,则最后一行有一个)。
Example:
<table>
<tr>
<td>old1</td> <td>old2</td>
</tr>
<tr>
<td>old3</td> <td>old4</td>
</tr>
</table>
To this:
<table>
<tr>
<td>NEW</td> <td>old1</td>
</tr>
<tr>
<td>old2</td> <td>old3</td>
</tr>
<tr>
<td>old4</td>
</tr>
</table>
注意自动添加的row.
我将向您展示三种方法来实现您的需求,
-
css3 Using
flex
(modern仅限浏览器)
-
css Using
inline-table
(问题与单元高度但可以用作sort-of倒退)
-
jquery使用标准
<table>
(所有浏览器!)
使用CSS3的FLEX
.table{
display: flex;
flex-wrap: wrap;
}
.cell{
width:50%;
background:#ddd;
}
<div class="table">
<div class="cell">NEW</div>
<div class="cell">OLD1</div>
<div class="cell">OLD2</div>
<div class="cell">OLD3<br>new line</div>
<div class="cell">OLD4</div>
</div>
Using inline-table
(单元格高度问题)
display: table;
对于父元素和
display: inline-table
对于内部 DIV:
.table{
display:table;
}
.cell{
display:inline-table;
width:50%; /* With percentage you simulate "how-many-per-Row" */
background:#ddd;
}
<div class="table">
<div class="cell">NEW</div>
<div class="cell">OLD1</div>
<div class="cell">OLD2</div> <!-- Works but notice this cell height -->
<div class="cell">OLD3<br>new line</div>
<div class="cell">OLD4</div>
</div>
你可以使用inline-table
作为旧版浏览器的后备方案 - 它不是完全相同的结果,但如果没有 JavaScript,它是您可以获得的最好结果。
Take a look in the specs about the display
property: https://developer.mozilla.org/en-US/docs/Web/CSS/display
Using <table>
, <tr>
and <td>
和 JavaScript (jQuery)
如果你想坚持优秀table
您可以使用“一点”jQuery 元素。
在这种情况下,情况会更复杂一些(请参阅代码注释):
jQuery(function($){ // DOM is now ready
var $table = $("table"); // Get your table
var maxRowCells = 2; // only 2-per-Row
var counter = 0; // just a dummy counter
function prependNewCell(){
var $newCell = $("<td/>", {html: "NEW"+(++counter)});
// Is the last row full?
if($table.find("tr:last td").length == maxRowCells){
// If true, append a new TR to TABLE to shift TD's to
$table.append( $("<tr/>") );
}
// Shift all last TD's to the next row:
$table.find("tr:not(:last)").each(function(){
var $tdLast = $(this).find("td").last();
$(this).next("tr").prepend( $tdLast );
});
// Finally. Prepend the new TD element to the first TR
$table.find("tr").first().prepend( $newCell );
}
$("button").on("click", prependNewCell);
});
td{
width:50%;
background:#ddd;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>ADD NEW CELL ON TOP</button>
<table>
<tr>
<td>OLD1</td>
<td>OLD2</td>
</tr>
<tr>
<td>OLD3</td>
<td>OLD4</td>
</tr>
</table>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)