我正在创建一个 jQuery,通过删除所有额外的行和列来优化表结构:
- a) 包含少于 2 个子元素
- b) 包含重复容器(
.column
不能有子.column
,.row
可以没有子.row
)
我仍然没有让它工作,它运行了 6 个步骤(在评论中可见)。
将#example
转变为#solution
需要什么?
var selection;
//1. Select all rows and columns
selection = $('#example').find('.row, .column');
//2. Deselect rows and columns with more than 1 child
selection = selection.not('.row:has(div:nth-of-type(2)), .column:has(div:nth-of-type(2))');
//3. Deselect rows and columns that contain cells
selection = selection.not('.row:has(.cell:nth-of-type(1)), .column:has(.cell:nth-of-type(1))');
//4. Remove redundant divs
console.log(selection);
//selection.css('border', '1px yellow solid');//paint them yellow (for testing)
selection.children().first().unwrap();
//5. Select duplicate rows and columns
selection = $('#example').find('.row:has(.row), .column:has(.column)');
//6. Remove redundant divs since first removal
selection.children().first().unwrap();
.grid {
display: flex;
min-height: 5px;
}
.row {
display: flex;
flex-grow: 1;
border: 1px solid red;
}
.cell {
flex-grow: 1;
flex-basis: 20px;
border: 1px solid green;
}
.column {
display: flex;
flex-grow: 1;
flex-direction: column;
border: 1px solid blue;
}
.row,
.column,
.cell {
margin: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span>Example</span>
<div id="example" class="grid">
<div class="column">
<div class="row">
<div class="column">
<div class="row">
<div class="column">
<div class="cell">
</div>
</div>
</div>
</div>
<div class="column">
<div class="row">
<div class="cell">
</div>
<div class="cell">
</div>
</div>
</div>
</div>
</div>
</div>
<span>Solution</span>
<div id="solution" class="grid">
<div class="row">
<div class="cell">
</div>
<div class="cell">
</div>
<div class="cell">
</div>
</div>
</div>
最佳答案
根据您给出的公式,试试这个demo
$('#example').find('.column').each(function(){
$(this).find(".column").each(function(){
$(this).unwrap();
});
if ($(this).children().size() < 2 && $(this).find(".cell").size() == 0 )
{
$(this).remove();
}
});
$('#example').find('.row').each(function(){
$(this).find(".row").each(function(){
$(this).unwrap();
});
if ($(this).children().size() < 2 && $(this).find(".cell").size() == 0 )
{
$(this).remove();
}
});
关于javascript - jQuery 从空列和行中清理 Flexbox 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35864699/