3 * 3 顯示圖片,間距爲10像素。當時我想自己實現個正方形,時間緊、任務重,就藉助了uni-gid;又想:nth-child(an+b)來給不同位置的圖片設置樣式,時間緊、任務重就:nth-child(1),:nth-child(4),:nth-child(7)...
實現個正方形
.parent-wrap {
width: 200px;
}
.parent-wrap .square {
float: left;
width: calc(33.3% - 7px);
padding-top: calc(33.3% - 7px);
background-color: red;
margin-bottom: 10px;
}
.parent-wrap .square:nth-child(3n-2),
.parent-wrap .square:nth-child(3n-1) {
margin-right: 10px;
}
<div class="parent-wrap">
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
</div>
padding-top: calc(33.3% - 7px);
我當時以爲是按照自身的寬度寫的100%,實際上是按照父元素的寬度。 三個格子間距就按21算,每個格子寬度33% - 7px,所以和witdh元素保持一致即可。
可以直接把.square 換成 img標籤,padding-top換成height即可,而無需使用絕對定位的方式
:nth-child(3n-2),:nth-child(3n-1)
這裏就用到高中數學知識了,元素的順序是按照1開始的
1 | 2 | 3 |
4 | 5 | 6 |
7 | 8 | 9 |
但運用到an+b中,n是從0開始的,當時也以爲是從1開始,還有...總之當時的腦子很亂。
倒着推更省事,3、6、9 是 3n,那麼2、5、8就是3n-1,1、4、7就是3n-2
n爲0時,3n-1是-1,3n-2是-2,都不會起作用。
1 | 2 | 3 | 4 |
5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 |
規律就是4n、4n-1、4n-2、4n-3,以此類推。
真是失之毫釐,差之千里,就如同自己一個人練習投籃和打比賽的區別,業務開發中干擾因素有很多,這時候基礎再不紮實可能就死在第一步了,汗顏、汗顏。
回到uni-grid的源碼,本質上就是獲取父元素的寬度然後均分給子元素,這有個弊端,那就是父元素一開始必須要有寬度,而不能由子元素撐開,而自己實現則靈活的多,比如藉助vw。
uni
.createSelectorQuery()
.in(this)
.select(`#${this.elId}`)
.boundingClientRect()
.exec((ret) => {
this.width = parseInt((ret[0].width - 1) / this.column) + "px";
fn(this.width);
});
// #endif
// #ifdef APP-NVUE
dom.getComponentRect(this.$refs["uni-grid"], (ret) => {
this.width = parseInt((ret.size.width - 1) / this.column) + "px";
fn(this.width);
});
前端工程化文章推薦:
對代碼零入侵的 mock 解決方案,按項目、請求路徑生成 js 文件,數據隨意定製