学习笔记.js瀑布流
花了点时间搞懂js的瀑布流思路,参考了网上相关教程。
思路大致为:
1.布局。考虑要实现多少列,利用Html和css将结构样式确定下来。先尝试加进几张图片,看看效果。
2.获取每一列高度。这是关键,关系到时候添加图片的位置。
3.返回最小列的高度。
4.添加图片。用到返回的高度,将图片加到每一次的列高最小处。利用计时进行批量添加。
5.实现滚动刷新。判断屏幕高度与滚动条头部之和是否大于可滚动的最大高度,进行无限次滚动刷新。不过,编写的代码有的浏览器没法起作用。
代码如下:
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>瀑布流</title><style type="text/css">body{margin: 0;padding: 0;background-color: #dedede;}.container{margin: 0 auto;width: 1000px;height: 500px;/*border: 1px solid #f00;*/display: flex;//弹性布局flex-direction:row;}.container>.box{flex: 1;/*border: 1px solid #f00;*/margin: 10px;}.box>img{width:100%;margin-top: 3px;border: 6px solid #fff;transition: all 0.2s ease-in-out;}.box>img:hover{transform: scale(1.05);cursor: pointer;box-shadow: 0 0 5px #000;}</style>
</head>
<body><div class="container"><div class="box" id="pb1"></div><div class="box" id="pb2"></div><div class="box" id="pb3"></div><div class="box" id="pb4"></div><script>/*定义一个窗口的最大高度*/var windowHeight=window.screen.height+500;var imgId=0;/*加载实现*/window.onload=function(){insert();/*添加一个监听事件,对象为滚动条*/window.document.addEventListener("scroll",function(){if(window.screen.height+document.documentElement.scrollTop>document.documentElement.scrollHeight)/*window.screen.height为当前屏幕高度document.documentElement.scrollTop为滚动高度document.documentElement为能够滚动的最大高度*/{windowHeight+=500;/*在原来基础上增加500*/insert();// console.log(window.screen.height);}});}var insert=function(){var inter=setInterval/*计时器*/(function(){if(document.documentElement.scrollHeight>windowHeight){clearInterval(inter);}var mD=minDiv();// console.log(mD);imgId++;/*源文件夹只有6张图,如果为7置为1*/if(imgId==7){imgId=1;}/*添加图片*/var img=document.createElement("img");//创建元素img.setAttribute("src","有的没的/"+imgId+".jpg");//设置元素属性mD.appendChild(img);},100);//放入元素}function minDiv(){/*获取元素*/var pb1=document.getElementById("pb1"); var pb2=document.getElementById("pb2");var pb3=document.getElementById("pb3");var pb4=document.getElementById("pb4");/*获取元素对象*/var pb1Image=pb1.children;var pb2Image=pb2.children;var pb3Image=pb3.children;var pb4Image=pb4.children;/*获取元素对象的高度*/var pb1H=calculate(pb1Image);var pb2H=calculate(pb2Image);var pb3H=calculate(pb3Image);var pb4H=calculate(pb4Image);// console.log("第一列:"+pb1H);// console.log("第二列:"+pb2H);// console.log("第三列:"+pb3H);// console.log("第四列:"+pb4H);/*获取最小元素对象高度*/var minPbH=Math.min(pb1H,pb2H,pb3H,pb4H);if(minPbH==pb1H){return pb1;}if(minPbH==pb2H){return pb2;}if(minPbH==pb3H){return pb3;}if(minPbH==pb4H){return pb4;}}/*计算元素对象高度*/function calculate(pbImage){if(pbImage==null||pbImage.length==0){return 0;}else{var height=0;for(var i=0;i<pbImage.length;i++){var img=pbImage[i];var h=img.height;height+=h;}return height;}}</script></div></body>
</html>
还需要努力。
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
