瀑布流页面效果

瀑布流页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>瀑布流布局</title>
    <script src="./jquery.js">
    </script>
    <style>
        #all{
            position: relative;
        }
        .box{
            float: left;
        }
        
        .pic>img{
            width: 150px;/* 这里控制宽度*/
            height: auto;
        }
    </style>
</head>
<body>

<div id="all">
    <div class="box">
        <div class="pic">
            <img src="./img/1.jpg">
        </div>
    </div>
    <div class="box">
        <div class="pic">
            <img src="./img/4.jpg">
        </div>
    </div>
    <div class="box">
        <div class="pic">
            <img src="./img/3.png">
        </div>
    </div>
    <div class="box">
        <div class="pic">
            <img src="./img/2.jpg">
        </div>
    </div>
    <div class="box">
        <div class="pic">
            <img src="./img/5.jpeg">
        </div>
    </div>
</div>
</div>
</div>
<script>
    $(window).load(function(){
        waterfall();
		var dataInt={"data":[{"src":"./img/1.jpg"},{"src":"./img/2.jpg"},{"src":"./img/4.jpg"},{"src":"./img/5.jpeg"},{"src":"./img/3.png"}]}
		$(window).scroll(function(){
			if(checkScollSlide('all','box')){
				$.each(dataInt.data,function(key,value){
					var oBox=$("<div>").addClass("box").appendTo($("#all"));
					var oPic=$("<div>").addClass("pic").appendTo($(oBox));
					var oImg=$("<img>").attr("src",$(value).attr("src")).appendTo($(oPic));
				})
				waterfall();
			}
		})
    })
    function waterfall(){
        var $boxs=$("#all>div");
        var w=$boxs.eq(0).outerWidth();
        var cols=Math.floor($(window).width()/w);
        $('#all').width(w*cols).css("margin","0 auto");
        var hArr=[];
        $boxs.each(function(index,value){
            var h=$boxs.eq(index).outerHeight();
            if(index<cols){
                hArr[index]=h;
            }else{
                var minH=Math.min.apply(null,hArr);
                var minHIndex=$.inArray(minH,hArr);
// console.log(minH);
                $(value).css({
                    'position':'absolute',
                    'top':minH+'px',
                    'left':minHIndex*w+'px'
                })
                hArr[minHIndex]+=$boxs.eq(index).outerHeight();
            }
        });
    }
	//检查是否满足加载数据条件,parent 父元素id clsName 块元素类
	function checkScollSlide(parent,clsName){
		var oParent = document.getElementById(parent),
		aBoxArr = oParent.getElementsByClassName(clsName),
		// 最后一个box元素的offsetTop+高度的一半
		lastBoxH = aBoxArr[aBoxArr.length - 1].offsetTop + aBoxArr[aBoxArr.length - 1].offsetHeight / 2,
		//兼容js标准模式和混杂模式
		scrollTop = document.documentElement.scrollTop || document.body.scrollTop,
		height = document.documentElement.clientHeight || document.body.clientHeight;
		return lastBoxH < scrollTop + height ? true : false;
	}
</script>
</body>
</html>

the end !

posted @ 2018-01-16 16:40  小酱油  阅读(177)  评论(0编辑  收藏  举报