HTML前端实现瀑布流无限加载

瀑布流加载是一种不错的前端加载方式,用户的体验也还不错。本次尝试中涉及到布局、图片追加、滚动条监控的内容

coser街

主要实现步骤:计算获取高度最低列,添加图片到其下,定时器每次添加图片,下拉加载问题

0x01 布局

前端的布局使用到了flex弹性布局

前端显示图片部分的HTML代码:

<div class="gallary"><div class="imgBox" id="item1">div><div class="imgBox" id="item2">div><div class="imgBox" id="item3">div><div class="imgBox" id="item4">div>
div>

那么在css中这样设置即可:

.gallary{width: 70%;margin: 8px auto;padding: 5px 8px;background-color: #fff;display: flex;							/*设置felx布局*/flex-direction: row;					/*方向是横向(行)*/
}
.imgBox{flex: 1;								/*占比为1,有四列占比就是1/4*/padding: 0px;margin:10px 5px;width: 250px;
}
.imgBox img{width: 100%;margin:4px;transition: all 0.2s ease-in-out;		/*淡入淡出*/
}
.imgBox img:hover{cursor: pointer;transform: scale(1.05);	/*放大img*/box-shadow: 1px 1px 2px #777;
}
0x02 Javascript控制

要想获取最低高度的列,那么就需要获取每列的高度并取得最小列,返回其节点。

// 获取最小的列
function getMinDiv(){var it1 = $('#item1');var it2 = $('#item2');var it3 = $('#item3');var it4 = $('#item4');var it1Height = calHeight(it1.children());var it2Height = calHeight(it2.children());var it3Height = calHeight(it3.children());var it4Height = calHeight(it4.children());			// 计算函数单独写var minDiv = Math.min(it1Height, it2Height, it3Height, it4Height);if(minDiv == it1Height){ return it1; }else if(minDiv == it2Height){ return it2; }else if(minDiv == it3Height){ return it3; }else{ return it4; }
}// 计算列图片占用高度
function calHeight(imgs){if(imgs == null || imgs.length == 0 ){return 0;}else{var Height = 0;for (var i = 0; i < imgs.length; i++) {Height += imgs[i].height;}return Height;}
}

添加图片到对应列后:

// 插入图片
function insertImgs(windowHeight){var counter = 0;var inter = setInterval(function(){// console.log(windowHeight < document.documentElement.scrollHeight);if( windowHeight < document.documentElement.scrollHeight || counter>10){clearInterval(inter);	//清除定时器}var div = getMinDiv();var num = Math.floor((Math.random()*10)+1);		// 获取img目录下随机10张图片div.append('+num+'.jpg">');counter += 1;}, 100);
}

文档加载,同时监控滚动条高度,来决定是否加载新的图片:

$(function(){var windowHeight = window.screen.height+500;	// 屏幕高度+500,初始化图片加载占用限制高度var initHeight = windowHeight;var timer = null;					// 节流,防止滚动条多次执行事件insertImgs(windowHeight);			//第一次加载$(window).scroll(function(){clearTimeout(timer);// 已经滚动高度 + 屏幕高度 > 能滚动高度timer = setTimeout(function () {if($(document).scrollTop() + window.screen.height > document.documentElement.scrollHeight){insertImgs(windowHeight+=window.screen.height);}}, 1000);})
})
0x03 完整代码

打包给大家,有兴趣的可以下载参考:

  • 蓝奏云
  • 百度云
参考

主要参考如下文章:

  • 《Flex布局教程》
  • 《防抖和节流》

原文地址:https://blog.dyboy.cn/program/113.html


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部