当我按[enter]并单击[refresh]

时间:2015-06-11 01:06:20

标签: javascript jquery web

当我练习瀑布流布局时,它有类似的问题:

首次加载页面或单击[刷新]或按[F5]时,它看起来很糟糕。图像堆栈的每一列! enter image description here

但是当我在地址栏中按[enter]或用鼠标滚动时,它看起来不错。 enter image description here

那我怎么解决这个问题呢?非常感谢!

var dataPic=["1.jpg","2.jpg","3.jpg","4.jpg","5.jpg","6.jpg","7.jpg","8.jpg","9.jpg"];

var curtIndex=0;

$(document).ready(function(){	
	$(window).on("load",function(){
		init();			//initializes the display with 30 pictures,call loadPic()
		placePic();		//layout
	});
	$(window).scroll(function(){		
		while(scrollSlide()){	//whether it needs loading more pictures
			loadPic();			//div and img can be loaded dynamically
		}
		placePic();				//layout for the elements that are just loaded 
	});
});

function init(){	
	var i=30;
	do{
		loadPic();
	}while(i-- >= 0);
	placePic();
}

function initSlide(){
	var box=$(".box");
	var lastboxHeight=box.last().get(0).offsetTop;
	var documentHeight=$(document).height();
	return (lastboxHeight<documentHeight)?true:false;
}

function currentIndex(){
	if(curtIndex==9){
		curtIndex=0;
	}
	return curtIndex;
}


function loadPic(){
		var boxadd=$("<div>").addClass("box").appendTo($("#container"));
		var current=$("<div>").addClass("pic").appendTo(boxadd);
		$("<img>").attr("src","./img/"+dataPic[currentIndex()]).appendTo(current);
		curtIndex++;
}

function placePic(){
	var box=$(".box");
	var boxWidth=box.eq(0).width();
	var num=Math.floor($(window).width()/boxWidth);
	var boxArr=[];
	box.each(function(index,value){
		var boxHeight=box.eq(index).outerHeight(true);
		if(index<num){
			boxArr[index]=boxHeight;
		}
		else{
			var minboxHeight=Math.min.apply(null,boxArr);
			var minboxIndex=$.inArray(minboxHeight,boxArr);
			$(value).css({
				"margin":"10px",
 				"box-shadow":"2px 2px 2px rgba(0,0,0,.3)",
 				"border-radius": "4px",
				"position":"absolute",
				"top":minboxHeight,
				"left":box.eq(minboxIndex).position().left
			});
			boxArr[minboxIndex]+=box.eq(index).outerHeight(true);
		}
	});
	
}

function scrollSlide(){
	var box=$(".box");
	var lastboxHeight=box.last().get(0).offsetTop+Math.floor(box.last().height()/2);	
	var documentHeight=$(window).height();
	var scrollHeight=$(window).scrollTop();
	return (lastboxHeight<documentHeight+scrollHeight)?true:false;
}
*{
 	margin: 0px;
 	padding: 0px;
 }

#container{
	margin-left: auto;
	margin-right: auto;
}

 .box{	
 	margin:10px;
 	box-shadow:2px 2px 2px rgba(0,0,0,.3);
 	border-radius: 4px;
 	position: relative;
 	float: left; 
 }

 .pic img{
 	margin: 0px;
 	padding: 0px;
 	width:200px;
 	height: auto;
 	vertical-align: bottom;
 }
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<link rel="stylesheet" href="mystyle.css">
	
</head>
<body bgcolor="">
	
	<div id="container">
		
	</div>

	<script type="text/javascript" src="jquery-2.1.4.min.js"></script>
	<script src="testjs.js"></script>
</body>
</html>

0 个答案:

没有答案