How to implement waterfall flow plug-in using JS
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 src="images/1.png" class="waterfall-box"> <img src="images/2.png" class="waterfall-box"> <img src="images/3.png" class="waterfall-box"> <img src="images/4.png" class="waterfall-box"> <img src="images/5.png" class="waterfall-box"> <img src="images/6.png" class="waterfall-box"> ... </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 = 'absolute' // 核心语句 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('img') img.setAttribute('src', `images/${i+1}.png`) img.setAttribute('class', 'waterfall-box') 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, 'scroll', 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('load') } } proto.done = function () { this.on('done', function () { isLoading = false ... }) this.emit('done') }
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 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Methods and techniques on how to implement waterfall flow layout through pure CSS. Waterfall layout (Waterfall Layout) is a common layout method in web design. It arranges content in multiple columns with inconsistent heights to form an image. Waterfall-like visual effects. This layout is often used in situations where a large amount of content needs to be displayed, such as picture display and product display, and has a good user experience. There are many ways to implement a waterfall layout, and it can be done using JavaScript or CSS.

How to implement waterfall flow in CSS? The following article will introduce to you two ways to use CSS to implement waterfall flow. I hope it will be helpful to you!

To implement the append() method in native js, specific code examples are required. When writing JavaScript code, it is often necessary to add new content to specified elements in the web page. A common operation is to set the HTML content of the element through the innerHTML attribute. However, using the innerHTML attribute sometimes results in the loss of event listeners, styles, etc. inside the element. In order to better implement the function of adding content, we can implement an append() method ourselves. The append() method can

How to use HTML and CSS to implement waterfall flow card layout. In web development, waterfall flow card layout is a common and cool display method. The waterfall flow layout is characterized by irregular shapes of cards, and the height and position automatically adapt according to the amount of content and screen size, making the page more attractive and interactive. This article will introduce how to use HTML and CSS to implement waterfall flow card layout, and provide specific code examples. 1. HTML structure First, we need to create the HTML structure. In this example we will use a

CSS Layout Tutorial: The Best Way to Implement Waterfall Card Layout Introduction: In modern web design, waterfall card layout is a very popular layout method. It can effectively display a large amount of content and adapt to different screen sizes, giving users a good browsing experience. This article explains the best way to implement a waterfall card layout and provides specific code examples. 1. The principle of implementing waterfall flow layout The principle of waterfall flow layout is to arrange cards in different positions according to certain rules according to the height of different content.

How to use Vue to implement waterfall layout effects. Waterfall layout is a common web page layout method. It can automatically arrange content according to different heights to form a waterfall-like effect. In front-end development, we can use the Vue framework to implement waterfall layout effects. The following will introduce the specific implementation method and provide code examples. Introduce Vue and Masonry layout libraries. First, introduce the CDN links of Vue and Masonry layout libraries in the HTML file. The code is as follows: <script

With the popularity of mobile devices, WeChat mini programs have become the choice of more and more enterprises and individuals. However, in the development process of small programs, achieving the waterfall flow effect is a difficult task. This article will introduce how to use PHP to implement the text waterfall flow effect in WeChat applet. 1. How to implement the waterfall flow effect The waterfall flow effect refers to the visual effect of arranging elements of different heights in order to make it look like a waterfall. In the implementation of waterfall flow effect on the Web, the commonly used method is through CSS Column layout.

How to use HTML and CSS to implement waterfall flow grid layout. Waterfall flow grid layout is a common layout method that can make web page elements present a waterfall-like effect, giving users a better visual experience. This article will introduce how to use HTML and CSS to implement waterfall flow grid layout, and provide specific code examples. First, we need to prepare some HTML structure and CSS styles. The following is a basic HTML structure, which contains several elements that need to be displayed: <!DOCTYPEhtml&
