瀑布流以及分页加载
瀑布流又称瀑布流式布局,是比较流行的一种网站页面布局方式。视觉表现为参差不齐的多栏布局,最早采用此布局的是网站是 Pinterest,后逐渐在国内流行。
瀑布流效果
即多行等宽元素排列,后面的元素依次添加到其后,等宽不等高,根据图片原比例缩放直至宽度达到我们的要求,依次按照规则放入指定位置
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> /* #content { width: 100px; height: 100px; background: red; position: absolute; } */ html, body { height: 100%; width: 100%; background-color:#cccccc; } #main { height: 800px; width: 100%; overflow-y: scroll; position: relative; } .obox { width: 200px; position: absolute; border:3px solid #ffffff; } </style> </head> <body> <!-- <div id="content"> </div> --> <div id="main"> </div> </body> <script type="text/javascript"> //瀑布流 var arr = [];//定义一个数组,用来存储元素的高度长度等于列数 let dom = document.getElementById('main') let cloumn = parseInt(dom.clientWidth / 200) var scrollIndex = 0 function reload(index) { for (let i = 0; i < 100; i++) { let domChild = document.createElement('div') domChild.setAttribute('class', 'obox') let height = Math.floor(Math.random() * 100) domChild.style.height = height + 'px' domChild.style.backgroundColor = `rgba(${Math.random() * 255},${Math.random() * 255},${Math.random() * 255})` dom.appendChild(domChild) } } function change(scrollIndex) { let divChild = document.getElementsByClassName('obox') for (let j = scrollIndex * 100; j < divChild.length; j++) { if (j < cloumn) { divChild[j].style.left = (200 + 10) * j + 'px' divChild[j].style.top = 0 arr.push(divChild[j].offsetHeight); } else { let minIndex = Math.min.apply(null, arr); //取到arr的最小值 var index = 0 for (var i = 0; i < arr.length; i++) { if (arr[i] == minIndex) { index = i } } divChild[j].style.top = arr[index] + 10 + 'px' divChild[j].style.left = divChild[index].offsetLeft + 'px' arr[index] = arr[index] + divChild[j].offsetHeight + 10 } } } window.onload = function () { reload(0) change(0) } //按需加载//分页的形式也不是懒加载 dom.addEventListener('scroll', function () { let minIndex = Math.min.apply(null, arr); if ((dom.scrollTop + dom.clientHeight) - minIndex > 10) { scrollIndex++ reload(scrollIndex) change(scrollIndex) } }) </script> </html>
版权声明:本文为xubaoer原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。