瀑布流布局已成为当今非常普遍的图片展示方式,无论是pc还是手机等移动设备上。最近使用到了“懒加载”,现在更新一般,因为平时主要使移动端的开发所以库文件使用的是zepto.js 。当然也可以和jquery 通用。
代码如下:
function loadimglazy(node) { var lazynode = $('[node-type=imglazy]', node), mobileheight, lazyoffsetheight, tempheight, currentnodetop, imgobject, imgdatasrc, localurl; localurl = location.href; // 获取当前浏览器可视区域的高度 mobileheight = $(window).height(); return function(co) { var conf = { 'loadfirst': true, 'loadimg': true }; for (var item in conf) { if (item in co) { conf.item = co.item; } } var that = {}; var _this = {}; /** * [replaceimgsrc 动态替换节点中的src] * @param {[type]} tempobject [description] * @return {[type]} [description] */ _this.replaceimgsrc = function(tempobject) { var srcvalue; $.each(tempobject, function(i, item) { imgobject = $(item).find('img[data-lazysrc]'); imgobject.each(function(i) { imgdatasrc = $(this).attr('data-lazysrc'); srcvalue = $(this).attr('src'); if (srcvalue == '#') { if (imgdatasrc) { $(this).attr('src', imgdatasrc); $(this).removeattr('data-lazysrc'); } } }); }); }; /** * 首屏判断屏幕上是否出现imglazy节点,有的话就加载图片 * @param {[type]} i) { currentnodetop [description] * @return {[type]} [description] */ _this.loadfirstscreen = function() { if (conf.loadfirst) { lazynode.each(function(i) { currentnodetop = $(this).offset().top; if (currentnodetop < mobileheight + 800) { _this.replaceimgsrc($(this)); } }); } }; //当加载过首屏以后按照队列加载图片 _this.loadimg = function() { if (conf.loadimg) { $(window).on('scroll', function() { var imglazylist = $('[node-type=imglazy]', node); for (var i = 0; i < 5; i++) { _this.replaceimgsrc(imglazylist.eq(i)); } }); } }; that = { replaceimgsrc: _this.replaceimgsrc(), mobileheight: mobileheight, objisempty: function(obj) { for (var item in obj) { return false; } return true; }, destory: function() { if (_this) { $.each(_this, function(i, item) { if (item && item.destory) { item.destory(); } }); _this = null; } $(window).off('scroll'); } }; return that; };}
以上所述就是本文给大家分享的全部内容了,希望能够对大家熟练使用javascript有所帮助。