search
HomeWeb Front-endJS TutorialImplementing waterfall flow layout based on JavaScript (2)_javascript skills

The example in this article explains the detailed code of JavaScript implementation of waterfall flow layout, and shares it with everyone for your reference. The specific content is as follows

1. Create Html template

The idea is to first use a div container to hold all the content, then the div box is used to place the picture, and finally the div box_border is used as the picture frame. The code is as follows

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>瀑布流</title>
</head>
<body>
  <div class="container" id="container">
    <div class="box_border" id="box_border">

      <div class="box" id="box1">
        <img  src="/static/imghwm/default1.png"  data-src="image/01.jpg"  class="lazy" alt="Implementing waterfall flow layout based on JavaScript (2)_javascript skills" >
      </div>
  <!--把Box复制多份,这里因为代码重复省略了-->
    </div>
  </div>
</body>
</html>

2. Simply set styles through css

Mainly set horizontal placement, photo frame color, border, etc.

/*
边界不留空,背景黑灰
*/
body{
  margin: 0px;
  background: darkgray;
}
/*
总布局设置为相对布局
*/
.container{
  position: relative;
}
/*
设置box属性
*/
.box{
  padding: 5px;
  float: left;
}
/*设置图片边框阴影和圆角
*/
.box_border{
  padding: 5px;
  border: 1px solid #cccccc;
  box-shadow: 0px 0px 5px #ccc;
  border-radius: 5px;
}
/*设置图片格式*/
.box_border img{
  width: 150px;
  height: auto;
}



3.JS controls the number of pictures placed in each row

After the above CSS layout, the size of the browser window changes, and the number of pictures inside will also change. Now we need to use JS to fix the number of pictures in each row, which can achieve good results for screens of different sizes

/*
 用于加载其他函数
 */
window.onload = function(){
  setImgLocation("container");
}
/*
 设置图片个数
 */
function setImgLocation(parent){
  var cparent = document.getElementById(parent);//得到父节点
  var childArray = getChildNodes(cparent);//得到图片数量
  var imgWidth = childArray[0].offsetWidth;//获取照片宽度
  var screenWidth = document.documentElement.clientWidth;//获取浏览器宽度
  var count = Math.floor(screenWidth/imgWidth);//每行的个数
  cparent.style.cssText = "width:"+count*imgWidth+"px;margin: 0 auto;";//设置其宽度并居中

}


/*
 获取全部图片的个数
 */
function getChildNodes(parent){
  var childArray =[];//定义一个数组存放图片box
  var tempNodes = parent.getElementsByTagName("*");//获取父节点下的所有节点
  //循环添加class为box的节点
  for(var i = 0;i<tempNodes.length;i++){
    if(tempNodes[i].className == "box"){
      childArray.push(tempNodes[i]);
    }
  }
  return childArray;//返回所有的子节点
}
注意:针对不同屏幕大小显示的个数是不一样的 



4.JS implements static waterfall flow

First implement a static layout, that is, the browser will not automatically refresh new pictures when pulling down.
Implementing the permutation algorithm is very simple

  • 1. Save all the heights of the first row of images into an array
  • 2. Calculate the minimum height and corresponding position of the image in the first row
  • 3. Place the first picture after the first row at this position
  • 4. Reset the height of the position to the sum of the two images
  • 5. Loop all the remaining pictures in 2

Code:

/*
 用于加载其他函数
 */
window.onload = function(){
  setImgLocation("container");
}
/*
 设置图片个数及位置排列
 */
function setImgLocation(parent){
  var cparent = document.getElementById(parent);//得到父节点
  var childArray = getChildNodes(cparent);//得到图片数量
  var imgWidth = childArray[0].offsetWidth;//获取照片宽度
  var screenWidth = document.documentElement.clientWidth;//获取浏览器宽度
  var count = Math.floor(screenWidth/imgWidth);//每行的个数
  cparent.style.cssText = "width:"+count*imgWidth+"px;margin: 0 auto;";//设置其宽度并居中
  //定义数组,存放第一行照片高度
  var imgHArray = [];
  //循环遍历图片
  for(var i=0;i<childArray.length;i++){
    //如果图片在第一行则获取高度
    if(i<count){
      imgHArray[i] = childArray[i].offsetHeight;
    }else//否则把最小高度的填充剩余图片
    {
      var minHeight = Math.min.apply(null,imgHArray);//获取最小高度
      var minIndex = getMinIndex(minHeight,imgHArray);//获取最小高度对应的下标
      childArray[i].style.position = "absolute";//设置要填充的图片盒子为绝对布局,否则不能更换位置
      childArray[i].style.top = minHeight+"px";//设置要填充图片距顶高度
      childArray[i].style.left = childArray[minIndex].offsetLeft+"px";//设置要填充图片距左高度
      imgHArray[minIndex] += childArray[i].offsetHeight;//填充后把当前位置高度设为两个图片相加
      //开始下一轮循环
    }

  }

}
/*
 获取最小高度对应的下标
 */
function getMinIndex(minHeight,imgHArray){
  for(var i in imgHArray){
    if(imgHArray[i] == minHeight){
      return i;
    }
  }
}
/*
 获取全部图片的个数
 */
function getChildNodes(parent){
  var childArray =[];//定义一个数组存放图片box
  var tempNodes = parent.getElementsByTagName("*");//获取父节点下的所有节点
  //循环添加class为box的节点
  for(var i = 0;i<tempNodes.length;i++){
    if(tempNodes[i].className == "box"){
      childArray.push(tempNodes[i]);
    }
  }
  return childArray;//返回所有的子节点
}

5.js realizes dynamic loading

Dynamic loading means that the scroll bar never slides to the bottom. To solve dynamic loading we need to consider two issues:
1). When to load?
Sliding distance + browser height>Distance between the last picture and the top
2). How to load?
By creating a new node, add the created node to it
Final code:

/*
 用于加载其他函数
 */
window.onload = function() {
  var cparent = document.getElementById("container");//得到父节点
  setImgLocation(cparent);
  //设置加载的图片
  var data = ["image/01.jpg", "image/02.jpg", "image/03.jpg", "image/04.jpg", "image/05.jpg", "image/06.jpg", "image/07.jpg", "image/08.jpg", "image/09.jpg",
    "image/11.jpg", "image/12.jpg", "image/13.jpg", "image/14.jpg", "image/15.jpg", "image/16.jpg", "image/17.jpg"];
  //滑动监听
  window.onscroll = function () {
    if (checkLoad(cparent)) {
      for (var i = 0; i < data.length; i++) {
        //创建新的节点
        var div1 = document.createElement("div");
        div1.className = "box";
        var div2 = document.createElement("div");
        div2.className = "box_border";
        var img = document.createElement("img");
        img.className = ".box_border img";
        img.src = data[i];
        div2.appendChild(img);
        div1.appendChild(div2);
        cparent.appendChild(div1);
      }
      setImgLocation(cparent);//创建节点后重新排列
    }
  }
}


/*
检查是否应该加载
 */
function checkLoad(cparent){
  var childArray = getChildNodes(cparent);//得到图片个数
  var lastImgHight = childArray[childArray.length-1].offsetTop;//得到最后一张图片距离顶部高度
  var scrollHeight = document.documentElement.scrollTop||document.body.scrollTop;//获得滑动距离(浏览器兼容性真烦人)
  var browserHeight = document.documentElement.clientHeight;//获得浏览器高度
  if(lastImgHight < scrollHeight+browserHeight){//判断是否加载
    return true;
  }else {
    return false;
  }
}
/*
 设置图片个数及位置排列
 */
function setImgLocation(cparent){

  var childArray = getChildNodes(cparent);//得到图片数量
  var imgWidth = childArray[0].offsetWidth;//获取照片宽度
  var browserWidth = document.documentElement.clientWidth;//获取浏览器宽度
  var count = Math.floor(browserWidth/imgWidth);//每行的个数
  cparent.style.cssText = "width:"+count*imgWidth+"px;margin: 0 auto;";//设置其宽度并居中
  //定义数组,存放第一行照片高度
  var imgHArray = [];
  //循环遍历图片
  for(var i=0;i<childArray.length;i++){
    //如果图片在第一行则获取高度
    if(i<count){
      imgHArray[i] = childArray[i].offsetHeight;
    }else//否则把最小高度的填充剩余图片
    {
      var minHeight = Math.min.apply(null,imgHArray);//获取最小高度
      var minIndex = getMinIndex(minHeight,imgHArray);//获取最小高度对应的下标
      childArray[i].style.position = "absolute";//设置要填充的图片盒子为绝对布局,否则不能更换位置
      childArray[i].style.top = minHeight+"px";//设置要填充图片距顶高度
      childArray[i].style.left = childArray[minIndex].offsetLeft+"px";//设置要填充图片距左高度
      imgHArray[minIndex] += childArray[i].offsetHeight;//填充后把当前位置高度设为两个图片相加
      //开始下一轮循环
    }

  }

}
/*
 获取最小高度对应的下标
 */
function getMinIndex(minHeight,imgHArray){
  for(var i in imgHArray){
    if(imgHArray[i] == minHeight){
      return i;
    }
  }
}
/*
 获取全部图片的个数
 */
function getChildNodes(parent){
  var childArray =[];//定义一个数组存放图片box
  var tempNodes = parent.getElementsByTagName("*");//获取父节点下的所有节点
  //循环添加class为box的节点
  for(var i = 0;i<tempNodes.length;i++){
    if(tempNodes[i].className == "box"){
      childArray.push(tempNodes[i]);
    }
  }
  return childArray;//返回所有的子节点
}

I hope this article will be helpful to everyone learning JavaScript programming.

Statement
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
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool