search
HomeWeb Front-endJS TutorialHow to implement waterfall flow plug-in using JS

How to implement waterfall flow plug-in using JS

Jun 07, 2018 pm 02:28 PM
Native jsWaterfalls flow

This article gives you a detailed analysis of a native JS waterfall plug-in and code-related explanations. Readers who are interested in this can refer to it.

The pictures in the waterfall flow layout have a core feature—equal width and variable height. The waterfall flow layout is used to a certain extent on domestic websites, such as pinterest, petals.com, etc. Then based on this feature, we will start the waterfall flow exploration journey.

Basic function implementation

First we define a container with 20 pictures.

<body>
 <style>
  #waterfall {
   position: relative;
  }
  .waterfall-box {
   float: left;
   width: 200px;
  }
 </style>
</body>
<p id="waterfall">
  <img  class="waterfall-box lazy"  src="/static/imghwm/default1.png"  data-src="images/1.png"    alt="How to implement waterfall flow plug-in using JS" >
  <img  class="waterfall-box lazy"  src="/static/imghwm/default1.png"  data-src="images/2.png"    alt="How to implement waterfall flow plug-in using JS" >
  <img  class="waterfall-box lazy"  src="/static/imghwm/default1.png"  data-src="images/3.png"    alt="How to implement waterfall flow plug-in using JS" >
  <img  class="waterfall-box lazy"  src="/static/imghwm/default1.png"  data-src="images/4.png"    alt="How to implement waterfall flow plug-in using JS" >
  <img  class="waterfall-box lazy"  src="/static/imghwm/default1.png"  data-src="images/5.png"    alt="How to implement waterfall flow plug-in using JS" >
  <img  class="waterfall-box lazy"  src="/static/imghwm/default1.png"  data-src="images/6.png"    alt="How to implement waterfall flow plug-in using JS" >
  ...
 </p>
由于未知的 css 知识点,丝袜最长的妹子把下面的空间都占用掉了。。。
接着正文,假如如上图,每排有 5 列,那第 6 张图片应该出现前 5 张图片哪张的下面呢?当然是绝对定位到前 5 张图片高度最小的图片下方。
那第 7 张图片呢?这时候把第 6 张图片和在它上面的图片当作是一个整体后,思路和上述是一致的。代码实现如下:
Waterfall.prototype.init = function () {
 ...
 const perNum = this.getPerNum() // 获取每排图片数
 const perList = []       // 存储第一列的各图片的高度
 for (let i = 0; i < perNum; i++) {
  perList.push(imgList[i].offsetHeight)
 }
 let pointer = this.getMinPointer(perList) // 求出当前最小高度的数组下标
 for (let i = perNum; i < imgList.length; i++) {
  imgList[i].style.position = &#39;absolute&#39; // 核心语句
  imgList[i].style.left = `${imgList[pointer].offsetLeft}px`
  imgList[i].style.top = `${perList[pointer]}px`

  perList[pointer] = perList[pointer] + imgList[i].offsetHeight // 数组最小的值加上相应图片的高度
  pointer = this.getMinPointer(perList)
 }
}

Careful friends may have discovered the code to obtain pictures. The height of the offsetHeight attribute is used. The sum of the heights of this attribute is equal to the image height inner margin border. Because of this, we use padding instead of margin to set the image and image. the distance between. In addition to the offsetHeight attribute, you must also understand the differences between offsetHeight, clientHeight, offsetTop, scrollTop and other attributes. , in order to better understand this project. The css code is simple as follows:

.waterfall-box {
 float: left;
 width: 200px;
 padding-left: 10px;
 padding-bottom: 10px;
}

Implementation of scroll and resize event monitoring

After implementing the initialization function init, the next step is to implement monitoring of the scroll event. This achieves the effect of a steady stream of pictures being loaded when scrolling to the bottom of the parent node. One point to consider at this time is, at what position is the loading function triggered when scrolling? This varies from person to person. My approach is to trigger the loading function when the condition of parent container height scrolling distance> offsetTop of the last picture is met, that is, orange line purple line> blue line, code As follows:

window.onscroll = function() {
 // ...
 if (scrollPX + bsHeight > imgList[imgList.length - 1].offsetTop) {// 浏览器高度 + 滚动距离 > 最后一张图片的 offsetTop
  const fragment = document.createDocumentFragment()
  for(let i = 0; i < 20; i++) {
   const img = document.createElement(&#39;img&#39;)
   img.setAttribute(&#39;src&#39;, `images/${i+1}.png`)
   img.setAttribute(&#39;class&#39;, &#39;waterfall-box&#39;)
   fragment.appendChild(img)
  }
  $waterfall.appendChild(fragment)
 }
}

Because the parent node may customize the node, an encapsulation of the scroll monitoring function is provided. The code is as follows:

proto.bind = function () {
  const bindScrollElem = document.getElementById(this.opts.scrollElem)
  util.addEventListener(bindScrollElem || window, &#39;scroll&#39;, scroll.bind(this))
 }
 const util = {
  addEventListener: function (elem, evName, func) {
   elem.addEventListener(evName, func, false)
  },
 }

Resize event monitoring is similar to scroll event monitoring. When triggered resize function, just call the init function to reset.

Use the publish-subscribe model and inheritance to implement listening binding

Since the goal is to develop plug-ins, we cannot just be satisfied with the realization of functions, but also leave corresponding operating space for developers to do their own work deal with. Reminiscing about the drop-down loading of pictures in waterfall flows in business scenarios, they are usually obtained asynchronously through Ajax, so the loaded data must not be hard-coded in the library. It is expected that the following calls can be implemented (the usage of waterfall is used here for reference),

const waterfall = new Waterfall({options})
waterfall.on("load", function () {
 // 此处进行 ajax 同步/异步添加图片
})

Observing the calling method, it is not difficult to think of using the publish/subscribe model to implement it. Regarding the publish/subscribe model, it was introduced before in Node.js Asynchronous Async Record. The core idea is to add the function to the cache through the subscription function, and then implement the asynchronous call through the publishing function. The code implementation is given below:

function eventEmitter() {
 this.sub = {}
}
eventEmitter.prototype.on = function (eventName, func) { // 订阅函数
 if (!this.sub[eventName]) {
  this.sub[eventName] = []
 }
 this.sub[eventName].push(func) // 添加事件监听器
}
eventEmitter.prototype.emit = function (eventName) { // 发布函数
 const argsList = Array.prototype.slice.call(arguments, 1)
 for (let i = 0, length = this.sub[eventName].length; i < length; i++) {
  this.sub[eventName][i].apply(this, argsList) // 调用事件监听器
 }
}

Next, to enable Waterfall to use the publish/subscribe mode, just Let Waterfall inherit the eventEmitter function, the code is implemented as follows:

function Waterfall(options = {}) {
 eventEmitter.call(this)
 this.init(options) // 这个 this 是 new 的时候,绑上去的
}
Waterfall.prototype = Object.create(eventEmitter.prototype)
Waterfall.prototype.constructor = Waterfall

The inheritance method absorbs the advantages of two methods of writing based on constructor inheritance and prototype chain inheritance, and uses Object.create isolation Now that we have subclasses and parent classes, we can write another article for more details about inheritance, so we’ll stop here.

Small optimization

In order to prevent the scroll event from triggering multiple loading of images, you can consider using function anti-shake and throttling. Based on the publish-subscribe model, an isLoading parameter is defined to indicate whether it is loading, and whether to load is determined based on its Boolean value. The code is as follows:

let isLoading = false
const scroll = function () {
 if (isLoading) return false // 避免一次触发事件多次
 if (scrollPX + bsHeight > imgList[imgList.length - 1].offsetTop) { // 浏览器高度 + 滚动距离 > 最后一张图片的 offsetTop
  isLoading = true
  this.emit(&#39;load&#39;)
 }
}
proto.done = function () {
 this.on(&#39;done&#39;, function () {
  isLoading = false
  ...
 })
 this.emit(&#39;done&#39;)
}

At this time, you need to add # at the place of the call. ##waterfall.done, thereby informing that the current image has been loaded. The code is as follows:

const waterfall = new Waterfall({})
waterfall.on("load", function () {
 // 异步/同步加载图片
 waterfall.done()
})

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

The life cycle of Vue components and Route (detailed tutorial)

Use SpringMVC to solve vue cross-domain requests

New features of webpack 4.0.0-beta.0 version (detailed tutorial)

The above is the detailed content of How to implement waterfall flow plug-in using JS. For more information, please follow other related articles on the PHP Chinese website!

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
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.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.