Home Web Front-end JS Tutorial Implementing waterfall flow layout based on JavaScript (2)_javascript skills

Implementing waterfall flow layout based on JavaScript (2)_javascript skills

May 16, 2016 pm 03:18 PM
javascript Waterfalls flow

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="image/01.jpg">
      </div>
  <!--把Box复制多份,这里因为代码重复省略了-->
    </div>
  </div>
</body>
</html>

Copy after login

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;
}



Copy after login

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;//返回所有的子节点
}
注意:针对不同屏幕大小显示的个数是不一样的 



Copy after login

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;//返回所有的子节点
}

Copy after login

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;//返回所有的子节点
}
Copy after login

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

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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles