Home > Web Front-end > JS Tutorial > Teach you step by step how to implement waterfall flow layout using js

Teach you step by step how to implement waterfall flow layout using js

藏色散人
Release: 2023-04-05 15:47:48
forward
2518 people have browsed it

This article brings you relevant knowledge about JavaScript. It mainly talks about how to use js to implement waterfall flow layout. There are code examples. Friends who are interested can take a look below. I hope it will be helpful to everyone. helpful.

Take you step by step to conquer the waterfall flow layout

Preface

The waterfall flow layout is more popular now A page layout method, that is, multiple lines of equal width elements are arranged, equal width and unequal height , and the following elements are added to the end of the previous line in turn Short elements below .

It can effectively reduce the complexity of the page and save a lot of space; moreover, the uneven arrangement of the waterfall flow can display multiple pieces of data to the user through the interface, and allow the user to There is an urge to browse down, providing a great user experience! For example, Taobao's page adopts this layout method. Let me show you the renderings of

Taobao's waterfall flow layout (mobile version) and the renderings we want to achieve (PC version) )~

Teach you step by step how to implement waterfall flow layout using jsTeach you step by step how to implement waterfall flow layout using jsThought preparation

By understanding the waterfall flow layout, let’s sort out the steps to implement it to facilitate our code writing.

1. First, we need to prepare

many pictures (I prepared 40 pictures), and vscode development tools.

2. Write the

front-end code and add a style to the image so that the image is of equal width and displayed in the same row .

3. Write

js code, you need to know the number of pictures in the first line, the serial number of the next picture and the previous line The sequence number of the shortest element, and the position .

Text

1. Front-end code writing

1. First, we define a

container container to hold all images, use box container to load box-img container and then load each picture in this container, which will facilitate the writing of styles later.

2. Make the picture

appear in the same row - use the float:left; attribute for the box container.

3. Let the image
be displayed with equal width - set

width:150px; to the box-img container, and set the img tag width:100%;Inherits 100% of the height of the parent container box-img.

4. In order to make the effect better-looking, we set the
padding, border and shadow
effects to the container holding the image.

The complete front-end code is attached:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>waterFall</title>
    <script src="./index.js"></script>
</head>
<style>
    *{
        margin: 0;
        padding: 0;
    }
    .container {
        overflow: hidden;
        position: relative;
    }
    .box{
        float: left;
        padding: 5px;
    }
    .box-img{
        width: 150px;
        padding: 5px;
        border: 1px solid #484848;
        box-shadow: 0 0 5px #484848;
    }
    .box-img img{
        width: 100%;
    }
</style>
<body>
    <div id="container">
        <div>
            <div>
                <img src="./img/1.jpg" alt="">
           </div>
        </div>
        /*.......后面接39个box,此处省略*/
    </div>
    
</body>
</html>
Copy after login
2. JS code writing

1. First, use window.onload=function(){} to load the page Function to be executed immediately after completion

In this function, we call the

imgLocation('container','box') function

to present the final effect, and the actual parameter passed in is

The parent container 'container' and the child container 'box' that holds the image.

window.onload=function() {
    imgLocation(&#39;container&#39;,&#39;box&#39;)
}
Copy after login
2. Implement the imgLocation() function

1) First we have to

get all the pictures to be placed

and store them in an
array Use document.getElementById(parent) to get the parent container;
Call the

getChildElement(cparent,content) method

, in this method, first get

All tags of the parent container, traverse all tags and use the if conditional statementto get the container with the class name box (a container that holds pictures), and save it Enter into a array that we built ourselves, and the return value is this array, which makes it easier to manipulate the position of the image through traversal later.

function imgLocation(parent,content){
    var cparent=document.getElementById(parent)
    //cparent下的所有的第一层的子容器 box
    var ccontent=getChildElement(cparent,content)//数组,40个div
}

//取到父容器中的某一层子容器
function getChildElement(parent,content){
    var contentArr=[]
    var allContent=parent.getElementsByTagName(&#39;*&#39;)//通过标签来选中得到一个数组
    //遍历allContent把其中类名为content的容器都存到contentArr数组中
    for(var i=0;i<allContent.length;i++){
        if(allContent[i].className==content){    //当前这个容器的类名是否为content
            contentArr.push(allContent[i])
        }
    }
    return contentArr;

}
Copy after login
2) After getting this array

, find out where
starts is the that needs to be placed in the position We use the following method:
First get the width of the

window

and

the width of each picture, divide the twoand Rounding down can get the number of pictures that can be placed in the first row. Naturally, we also know the serial number of the picture that we need tooperate .

    //从谁开始是需要被摆放位置的
    var winWidth=document.documentElement.clientWidth;//视窗宽度
    var imgWidth=ccontent[0].offsetWidth;//图片宽度

    var num=Math.floor(winWidth/imgWidth)//第一行能放几张图
Copy after login
3)得到需要被摆放位置的图片序号后,确定其摆放位置

我们自己定义一个存储高度的数组,对前一行元素的高度进行遍历存入数组,当遍历到需要被摆放位置的图片时,用Math.min()方法获取前一行高度最矮的元素高度,并用indexOf()方法获取到其下标

再对我们所操作的这个图片容器的样式调整
position:absolute;绝对定位top值设置为前一行高度最矮的图片高度minHeightleft值设置为单张图片宽度这张图片的下标minIndex。

最后,不要忘啦,摆放好图片后,还要更新摆放的那一列的高度哟~

    //操作num+1张图
    var BoxHeightArr=[]
    for(var i=0;i<ccontent.length;i++){
        //前num张只要计算高度
        if(i<num){
            BoxHeightArr[i]=ccontent[i].offsetHeight
        }
        else{
            //我们要操作的box  :ccontent[i]
            var minHeight=Math.min.apply(null,BoxHeightArr)//apply:把最小值这个方法借给它用
            var minIndex=BoxHeightArr.indexOf(minHeight)//返回数组下标
            ccontent[i].style.position=&#39;absolute&#39;//style设置样式
            ccontent[i].style.top=minHeight+&#39;px&#39;
            ccontent[i].style.left=imgWidth*minIndex+&#39;px&#39;

            //更新最矮的那一列的高度
            BoxHeightArr[minIndex]+=ccontent[i].offsetHeight
        }
    }
Copy after login

最终整合一下就可以实现瀑布流的布局效果啦!

最后

以上就是瀑布流布局的实现过程,看完本文如果觉得有用,记得点个赞支持,收藏起来说不定哪天就用上啦~
文章可能有一些错误,欢迎评论指出,也欢迎一起讨论。

推荐学习:《JavaScript视频教程

The above is the detailed content of Teach you step by step how to implement waterfall flow layout using js. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:juejin.im
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template