


JavaScript implements waterfall flow loading image principle_javascript skills
Let’s talk about the general principle, let’s take the picture first:
Function description:
- Load different data according to the attribute values of different menus
- Pull down the scroll bar to a certain position to preload the image, and render the html when the scroll bar is pulled to the bottom;
- Move the mouse to the menu to switch between various picture lists;
- Move the mouse over the picture list to display detailed information;
Technical implementation plan:
Let’s first sort out the process from loading to display:
1. Load data
2. Splice HTML and write it to the page
3. Check whether all the img in the HTML just written have been loaded. If so, go to 5, otherwise go to 4
4. Wait for the image to load
5. Calculate the position of each element
The biggest headache at the beginning was how to position it. Later, after a friend’s guidance, I finally solved it: calculate how many columns of pictures there are in total and put the height of each column into an array. Whenever an image is loaded, search for the smallest value in the array, and set the top of the current image to this value. After completion, add the height of the image to the smallest value in the array and return it to the array, in sequence. analogy.
PS: Because there are too many codes for this function, we can only do basic simple decomposition of the code:
// 创建用于记录每列高度的数组 _getLowestCol: function() { t._cols = new Array(5),min = 0; // 初始化为0 for (var i = 0; i < t._cols.length; i++) { if (cols[i] < cols[min]) { min = i; } return min; } }, _reposition: function() { t._grids.each(function(i, grid) { //先显示出来 grid = $(grid).show(); var height = grid.outerHeight(), min = t._getLowestCol(); // 定位 grid.animate({ left: (t._colWidth + t._colSpacing) * min, top: t._cols[min], opacity: 1 },1000); // 记录高度 t._cols[min] += height; }); }
The second difficulty encountered during the development process is: as shown in the picture above, moving the mouse to the menu bar requires switching the image list, and waterfall flow is required to load different types of data. Therefore, we have to deal with how to execute the code request interface only once for each page when switching pages, instead of re-requesting the data interface every time the page is switched, and only perform the operation of switching the display list of pictures.
Considering that each menu has a custom attribute, this problem is easily solved: create an object to record whether the current menu has executed code, and if not, execute the request data.
var isLoad = {};//是否载入过 labelType.mouseover(function() { var i = $(this).index(); var api = _this.attr('api');//接口标识 if(! isLoad[ api ]){ isLoad[ api ] = i; loadData(wrapper, api); } });
The following is the full code:
html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <style type="text/css"> *{margin:0;padding:0;} ul,li{ list-style-type:none;} li img{width:100%;list-style:none;} </style> </head> <body> <div class="photo_box"> <ul id="container" style="border:1px solid #000;width:80%;height:600px;overflow:hidden;margin:0 auto;position: relative;"> </ul> <div id="loading" class="loading" style="text-align: center;margin-top: 20px;font-size: 1.2em;">加载中...</div> <div id="more" class="more"style="text-align: center;margin-top: 20px;font-size: 1.2em;"><input type="button" value="更 多" id="clear" /></div> </div> <script type="text/javascript" src="../../lib/seajs/sea.js"></script> <script type="text/javascript" src="../../lib/base/1.0.x/base.js"></script> <script type="text/javascript"> seajs.use(['lib/jquery/1.11.x/index.js', '_example/waterFall_1.1/waterfall.js'], function($, waterFall) { waterFall.init({ container: $('#container'), dataURL: 'http://www.woxiu.com/index.php?action=Index/Main&do=ApiZhuboGrade', dataType: 'jsonp', template: '<% for (var i = 0; i < data.length; i++) { %>' + '<li style="display: none;">' + '<img src=" <%-data[i].room_img% alt="JavaScript implements waterfall flow loading image principle_javascript skills" > ">' + '</li>' + '<% } %>', colWidth: 200, colSpacing: 10, rowSpacing: 15, page: 1, pageEnd: 8, }); // 限制同时展示的页数 var loadCounter = 1; function pageNum(){ if (loadCounter >= 3) { $('#more').show(); $('#loading').hide(); return true; } else { loadCounter++; $('#more').hide(); $('#loading').show(); } return false; } $('#clear').click(function() { loadCounter = 1; waterFall._loadNext(); }); }); </script> </body>
js:
/** * 瀑布流布局组件类 * @param {Object} options 组件设置 * @param {NodeList} options.container 瀑布流容器 * @param {String} options.dataURL 数据地址 * @param {String} [options.dataType='jsonp'] 数据类型,json或jsonp * @param {String} options.template 模板编辑 * @param {Number} [options.colWidth] 图片大小。 * @param {Number} [options.colSpacing] 列间隔。 * @param {Number} [options.rowSpacing] 行间隔。 * @param {Number} [options.page=1] 数据开始页码 * @param {Number} [options.pageEnd] 数据末尾页码 * @pageNum() 函数,如果不需要现在加载也是,需要把函数里面的判断去掉。 从加载到显示的流程 1. 加载数据 2. 拼接HTML写入到页面 3. 检查刚刚写入的HTML中的img是否全部加载完成,如果是,进入5、否则进入4 4. 等待图片加载完成 5. 计算每个元素的位置 */ define(function(require, exports, module) { 'use strict'; var Tmpl = require('lib/tmpl/2.1.x/index.js'), $ = require('lib/jquery/1.11.x/index.js'); var waterFall = { init: function(options) { var t = this; t._container = options.container; t._template = options.template; t._colWidth = options.colWidth; t._colSpacing = options.colSpacing; t._rowSpacing = options.rowSpacing; t.dataURL = options.dataURL; t.dataType = options.dataType; t.page = options.page; t.pageEnd = options.pageEnd; t._switch = false; //计算有几列 总宽度 / (列宽 + 列间隔) t._totalCols = parseInt(t._container.width() / (t._colWidth + t._colSpacing)); // 创建用于记录每列高度的数组 t._cols = new Array(t._totalCols); // 初始化为0 for (var i = 0; i < t._cols.length; i++) { t._cols[i] = 0; } t._loadingPage = options.page || 0; t._loadNext(options); //下拉滚动条加载 var lastTime = new Date().getTime(); $(window).scroll(function() { if ( !t._switch ) { //判断是否滚动过快,在ie下 var thisTime = new Date().getTime(); if (thisTime - lastTime < 50) { console.log(thisTime - lastTime); lastTime = thisTime; return; } if ($(window).scrollTop() + $(window).height() >= document.documentElement.scrollHeight) { lastTime = thisTime; t._loadNext(); } } }); }, //加载器 _loadNext: function(t) { var t = this; t._switch = true; //请求数据 if (!t.trigger) { $.ajax({ url: t.dataURL, data: { page: ++t._loadingPage }, dataType:t.dataType, success: function(response){ t.trigger = t._completeLoading(response); }, error:function(){console.log('Error! 请求有误');} }); } return false; }, //加载完数据调用此函数 _completeLoading: function(result) { var t = this; if (t._loadingPage >= t.pageEnd) { $('#more').hide(); $('#loading').html('<p>已是最后一页了喔 ^_^ ^_^</p>'); return true; } else { //if (!pageNum()) { t._add(result); //}; } return false; }, //添加格子 _add: function(result) { var t = this, grids = ''; //调用模板 var content = Tmpl.render(t._template, {data:result.data}); //原始定位 t._grids = $(content).css({ position: 'absolute', left: t._container.width(), top: t._container.height(), width: t._colWidth, opacity: 0 }); //把Html添加到容器 t._container.append(t._grids); // 执行一次_reposition,如果所有图片都加载完成,该方法返回true,否则返回false if ( !t._reposition() ) { // 有图片未加载完,监听onload和onerror t._grids.find('img').bind('load error', function() { this.loaded = true; // 有图片加载完成,再次执行_reposition if (t._grids) { t._reposition(); } }); } }, // 此方法用于获取高度最低的列 _getLowestCol: function() { var cols = this._cols, min = 0; for (var i = 1; i < cols.length; i++) { if (cols[i] < cols[min]) { min = i; } } return min; }, //定位 _reposition: function() { var t = this, allImgsLoaded = true; // 检测图片是否全部加载完成 t._grids.find('img').each(function(i, img) { if (!img.loaded && !img.complete) { allImgsLoaded = false; } return allImgsLoaded; }); if (allImgsLoaded) { t._grids.each(function(i, grid) { //先显示出来 grid = $(grid).show(); var height = grid.outerHeight(), min = t._getLowestCol(); // 非第一行的时候,要加上行间隔 if (t._cols[min]) { t._cols[min] += t._rowSpacing; } // 定位 grid.animate({ left: (t._colWidth + t._colSpacing) * min, top: t._cols[min], opacity: 1 },1000); // 记录高度 t._cols[min] += height; }); // 重设外层容器高度为最高列高度 t._container.css( 'height', Math.max.apply(Math, t._cols) ); t._switch = false; delete t._grids; } return allImgsLoaded; }, } return waterFall; });
The above is the entire content of this article. I hope it will be helpful to everyone in learning javascript programming.

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.

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

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.

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.

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.


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

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

Hot Article

Hot Tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Zend Studio 13.0.1
Powerful PHP integrated development environment

WebStorm Mac version
Useful JavaScript development tools

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.