当前位置:网站首页>Waterfall flow layout
Waterfall flow layout
2022-07-25 16:01:00 【Gai Yuexi's boyfriend outside the circle (kuaixi)】
Catalog
demand
The so-called waterfall flow layout , It contains several columns of equal width , Place pictures in each column 、 Video etc. , The placed elements are of equal width , Therefore, it may be unequal . When new elements come , The lower column will be inserted , In this way, uneven 、 Visually, the layout is like a waterfall .
Let's simplify it here , As long as two columns of equal width layout show pictures .
Ideas
Two column layout , Use it directly flex The layout can be realized . however , It can't be set up here align-items by center, If set, the picture column will be centered , Does not conform to the visual effect of waterfall flow . I set left and right Two , The width of the two columns is equal , The structure and style are basically finished .
Then write JavaScript. The logic is , Judge the present left and right Height ( I use clientHeight), If on the left <= On the right , Then put it on the left , Otherwise, put it on the right . Go through all the pictures , Just put it in according to this logic .
Code implementation
html part
<!-- Waterfall flow parent container -->
<div class="container">
<!-- Two columns of equal width layout -->
<div class="col left"></div>
<div class="col right"></div>
</div>css part
.container {
width: 700px;
background-color: aliceblue;
margin: auto;
/* flex Layout */
display: flex;
align-items: flex-start;
}
.col {
flex-basis: 350px;
}
.col img {
/* Fix the width of the picture */
width: 100%;
}JavaScript part
// Get three elements
let container = document.getElementsByClassName('container')[0]
let left = document.getElementsByClassName('col')[0]
let right = document.getElementsByClassName('col')[1]
// Insert a picture
function initImg() {
for (let i = 1; i < 27; i++) {
let img = new Image();
img.src = "./pictures/" + i + ".jpg"
if (left.clientHeight <= right.clientHeight) {
left.appendChild(img)
} else {
right.appendChild(img)
}
}
}
initImg()As the code shows , Get the parent element and the left and right columns , Then traverse each picture , Judge the insertion in turn . It looks perfect , But is it true ?
Realization effect

It looks perfect , It also looks like a waterfall . But when I pull it to the bottom of the page, I find :

A large piece on the left is empty , All on the right . This is obviously not right , Because according to logic , Shorter on the left , It should be added on the left .
Problems and corrections
The problem is ,img Loading of is an asynchronous process . Let's look at the for loop :
// Insert a picture
function initImg() {
for (let i = 1; i < 27; i++) {
let img = new Image();
img.src = "./pictures/" + i + ".jpg"
if (left.clientHeight <= right.clientHeight) {
left.appendChild(img)
} else {
right.appendChild(img)
}
}
}new 了 Image After the object , Specified its src, Then immediately judge the height of the left and right sides . At this time ,img It's not loaded yet . However ,for The loop will not wait for it to load . After the next picture is generated , Will also judge immediately , But at this time, the previous picture has not been put on the page , So the left and right height is probably wrong , This leads to wrong judgments . This appears in the figure above , There are many pictures in the right column , And the left column is blank .
The solution is , Write this loop asynchronously , Only after the last picture is loaded , To judge the next picture .
It's easy to think , Use Promise Complete asynchronous judgment . But for the loop Promise, It is difficult to pass clearly then Change to advance . therefore , I decided to adopt async and await.
This requires another method to be encapsulated , This method returns Promise, stay Promise Load a picture in . Then traverse all the pictures , Use async/await, Call this method in turn , You can get the results .
And in the Promise in , When do we call resolve Well ? This requires monitoring img Of onload event , Set up onload Callback function for event , Call in callback function resolve that will do .
Through the analysis of , Improve the code again :
// Load first index A picture
function loadIndexImg(index) {
return new Promise((resolve, reject) => {
// Currently loaded pictures
let img = new Image();
img.src = './pictures/' + index + '.jpg'
img.onload = () => {
if (left.clientHeight <= right.clientHeight) {
left.appendChild(img)
} else {
right.appendChild(img)
}
resolve();
}
})
}
// Insert a picture
async function initImg() {
// After loading and inserting the picture, you can judge the next one , So we use async/await
for (let i = 1; i <= 26; i++) {
await loadIndexImg(i)
}
}
initImg()You can see , stay initImg in , In turn, calls loadIndexImg, And it is called asynchronously . Load the next picture after the picture is loaded , The effect should be ok .
Effect after correction

The effect is very good !!!
summary
This paper realizes a simple two column waterfall layout , You need to use Promise Wait for asynchronous operation .
边栏推荐
- 行云管家V6.5.1/2/3系列版本发布:数据库OpenAPI能力持续强化
- LeetCode - 641 设计循环双端队列(设计)*
- Leetcode - 707 design linked list (Design)
- Beyond compare 4 realizes class file comparison [latest]
- 产品动态丨Android 13 高效适配全新升级
- Huawei 2023 starts to warm up in advance! Zuo Shen's program code interview guide comes in handy
- Circulaindicator component, which makes the indicator style more diversified
- Leetcode - 303 area and retrieval - array immutable (design prefix and array)
- [server data recovery] data recovery cases of raid information loss caused by unexpected power failure of HP EVA server storage
- 一文入门Redis
猜你喜欢

Leetcode - 380 o (1) time to insert, delete and get random elements (design hash table + array)

Implementation of recommendation system collaborative filtering in spark

推荐收藏,这或许是最全的类别型特征的编码方法总结

leetcode:6127. 优质数对的数目【位运算找规律 + 两数之和大于等于k + 二分】

不愧是阿里内部“千亿级并发系统架构设计笔记”面面俱到,太全了

报表工具的二次革命

Pytoch learning notes -- seresnet50 construction

Pytoch learning notes -- Summary of common functions 3

Storage structure of cross linked list

Introduction to redis
随机推荐
Leetcode - 225 implements stack with queue
# JWT 图解
MySQL tutorial 71-where conditional query data
leetcode:528. 按权重随机选择【普通随机失效 + 要用前缀和二分】
Equivalent change of resistance circuit (Ⅱ)
Matlab simulation of BPSK modulation system (1)
How to solve cross domain problems
Activity review | July 6 Anyuan AI X machine heart series lecture No. 2 | MIT professor Max tegmark shares "symbiotic evolution of human and AI"
用GaussDB(for Redis)存画像,推荐业务轻松降本60%
Gary marcus: learning a language is more difficult than you think
Product upgrade observation station in June
泰雷兹推出解决方案,助力SAP客户控制云端数据
General test case writing specification
哪个led显示屏厂家更好
Gap Locks(间隙锁)
Introduction to redis
Window system black window redis error 20creating server TCP listening socket *: 6379: listen: unknown error19-07-28
Leetcode - 379 telephone directory management system (Design)
mysql意向锁
How Google cloud disk is associated with Google colab