首先還是來看一下效果圖
ps:因爲錄製的gif超出上傳gif大小限制,我們來用通過圖片看一下效果。
開始時候的滾動條位置
滑動之後再看
以及繼續滑動
好好好、下面直接看源碼以及思路講解
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>瀑布流</title>
<style>
*{
padding: 0;
margin: 0;
list-style: none;
}
.box{
width: 960px;
margin: 0 auto;
}
.box ul{
float: left;
width: 300px;
margin: 0 10px;
}
.box ul li img{
width: 300px;
margin-bottom: 15px;
}
</style>
<script>
window.onload = function(){
// 獲取元素
var oBox = document.getElementById('box');
var oUl = document.getElementsByTagName('ul');
var vH = document.documentElement.clientHeight;
// 循環動態添加
creaeElement();
function creaeElement(){
for(var i = 0 ; i < 21 ; i ++){
// 創建img標籤
var oImg = document.createElement('img');
oImg.src = 'images/' + i + '.jpg';
// 創建li標籤
var oLi = document.createElement('li');
oLi.appendChild(oImg);
//獲取最小ul的索引
var minIndex = checkHeight(oUl);
oUl[minIndex].appendChild(oLi);
}
}
//滾動事件
window.onscroll = function(){
var sTop = document.documentElement.scrollTop || document.body.scrollTop;
//滾動條的高度 + 瀏覽器的高度 = 內容區域的高度
if( sTop + vH > document.body.scrollHeight*0.8 ){
creaeElement();
}
}
}
// 獲取最小ul的索引
function checkHeight(oUl){
//初始化
var height = 1000000;
var index = 0;
for(var i = 0 ; i < oUl.length ; i++){
var nowHeight = oUl[i].offsetHeight;
if( nowHeight < height ){
height = nowHeight;
index = i;
}
}
return index ;
}
</script>
</head>
<body>
<pre>
原理:
1、外層容器浮動
2、判斷某一容器爲最小容器
3、將內容插到最小容器內
4、當滾動條滾動到一定程度 循環執行2和3
代碼要點:
1、創建元素 document.createElement('元素')
2、獲得屏幕的寬和高,如果不做橫向的瀑布,獲取高就可以
document.documentElement.clientHeight
3、滾動條事件window.onscroll
4、獲得滾動條高度
document.documentElement.scrollTop
document.body.scrollTop
5、滾動後body高度
document.body.scrollHeight
</pre>
<div id="box" class="box">
<ul></ul>
<ul></ul>
<ul></ul>
</div>
</body>
</html>
博主開通了一個關於前端分享的微信公衆號,有興趣的小夥伴歡迎關注:
公衆號:簡單的前端
不知道能不能推薦微信公衆號,如有違反,請告知