一個考驗基本功的功能,而我現在也才用了最流行的一種方法,希望看到的有思路的可以寫下自己的做法,一整段代碼如下:
實現思路:通過獲取父元素的寬度以及子元素寬度進行一系列計算,補齊最後一行,達到justify-content:wrap的時候,依舊完美左對齊
<html>
<head>
<title></title>
<style>
.input1{
width: 100px;
}
.parent{
display: flex;
flex-wrap: wrap;
justify-content: space-evenly;
width: 387px;
border: solid 1px #000;
}
.parent div{
width: 80px;
height: 80px;
}
.child1{
background: yellow;
}
.child2{
background: rgb(234, 0, 255);
}
.child3{
background: pink;
}
.child4{
background: rgb(255, 187, 0);
}
.child5{
background: green;
}
.child6{
background: rgb(0, 195, 255);
}
.childBlank{
background-color: #ffffff;
}
</style>
</head>
<body>
<div class="parent">
<div class="child1"></div>
<div class="child2"></div>
<div class="child3"></div>
<div class="child4"></div>
<div class="child5"></div>
<div class="child6"></div>
</div>
</body>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
<script>
function calcChild(){
console.log(1234568888)
var parentWidth = $(".parent").width();
var childWidth = $(".parent div").width();
var sumChild = $(".parent div").length;
console.log(parentWidth,childWidth,sumChild);
//每行最多個數
var maxNum = Math.floor(parentWidth/childWidth);
console.log(maxNum);
//最後一行缺多少個
if(sumChild > 0){
var needAddNum = (sumChild%maxNum);
console.log(needAddNum);
for(var i = 0;i<needAddNum;i++){
$(".parent").append("<div class='childBlank'></div>");
}
}
}
calcChild()
</script>
</html>
複製代碼就能看效果了,可是代碼並沒有實現監控父元素寬度變化,而去改變子元素的補充個數問題,大家可以自己搗鼓搗鼓。