刚开始接触js,就想写写经典的瀑布流,搜了下网上的教程,发现大多是用jquery写的,非常简单,用它也不用考虑兼容性的问题(jquery已经考虑到了),就想自己用原生的js写个简单的瀑布流模型,暂且没有考虑到拖动时自动排版的情形,以后再添加。(发现用原生的js果然步骤比较多啊!很多方法都很底层的!)
<!DOCTYPE HTML> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>waterfall flow</title> <style type="text/css" > body{margin:0px;} #main{width:840px;margin:0 auto;} .flow{float:left;width:200px;margin:5px;background:#ABC;} </style> </style> </head> <body> <div id="main"> <div class="flow" ></div> <div class="flow" ></div> <div class="flow" ></div> <div class="flow" ></div> </div> </body> <script type="text/javascript"> var flowlist = null; if(document.getElementsByClassName){ var flowlist = document.getElementsByClassName("flow"); } else{ /* 考虑IE的兼容性 */ var flowlist = getMElementsByClassName("div","flow"); } /* 初始化 */ addItems(flowlist,3); function getMElementsByClassName (tagname,classname) { var res = []; var elements = document.getElementsByTagName("div"); for (var i = 0; i < elements.length; i++) { if(elements[i].className == classname) res.push(elements[i]); }; return res; } function addItems(elements,times){ for (var j = 0; j < times; j++) { for (var i = 0; i < elements.length; i++) { var newnode = document.createElement("div"); newnode.style.background="#159"; newnode.style.width="90%"; newnode.style.height=getRandom(200,300)+"px"; newnode.style.margin="10px"; elements[i].appendChild(newnode); }; }; } /* 考虑兼容性,使用document.documentElement.scrollTop 使用DOM0事件 */ window.onscroll = function(){ // 被卷去的高度 var scrollTop = document.documentElement.scrollTop; // 页面高度 var pageHeight = document.body.scrollHeight; // 可视区域高度 var viewHeight = window.screen.availHeight; console.log("被卷去的高度:"+scrollTop + " "+"页面高度:"+pageHeight+" "+"可视区域高度:"+viewHeight); //当滚动到底部时 if((scrollTop+viewHeight)>(pageHeight-20)){ if(scrollTop<10000){//防止无限制的增长 addItems(flowlist,2); } } } function getRandom(min,max){ //x上限,y下限 var x = max; var y = min; if(x<y){ x=min; y=max; } var rand = parseInt(Math.random() * (x - y + 1) + y); return rand; } </script> </html>
效果图:
时间: 2024-12-07 04:25:49