图片预加载

 

http://www.w3school.com.cn/jsref/dom_obj_image.asp

 

<!doctype html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>demo1--http://www.bokicabo.com/en/04/</title>
	<style>
	*{padding: 0; margin: 0;}
	html,body{ height: 100%; margin: auto;}
	.parentBox{ width: 100%; height: 100%; position: relative; text-align: center; overflow: hidden; border:0px solid red;}
	.box1{ background: #f5f2ed;}
	.box2{ background: #dfb00d;}
	.box3{ background: #8d9d1c;}
	.box4{ background: #b42642;}
	.box5{ background: #26b0d4;}
	.box6{ background: #c76d18;}
	.box7{ background: #424041;}
	.parentBox img.pic{ position: absolute; height: 100%; width: auto !important;}
	</style>
	<script src="../jquery.js" type="text/javascript"></script>
	<script>
		 window.onload = function(){
	 		var aImg = document.getElementsByTagName("img");
		 	loadImg(aImg);
		 }
		 // 图片预加载
	 	function loadImg(obj){
		 	for(var i = 0; i< obj.length; i++){
		 		if(obj[i].complete){
		 			// 图片加载成功
		 			checkSize(obj[i]);
		 		}else{
		 			setTimeout(function(){loadImg();},100);
		 		}
		 	}		 		
	 	}
	 	// 设置图片位置
	 	function checkSize(obj){
	 		var l = -obj.width / 2 + "px";
	 		obj.style.marginLeft = l;
	 		// console.log(l);
	 	}
	 	$(function(){
		 	$(window).on("resize",function(){
		 		$(".parentBox .pic").each(function(i,eme){
		 			var l = Math.floor($(eme).outerWidth() / 2);
		 			$(eme).css("marginLeft",-l + "px");
		 		});
		 	});	 		
	 	});
	</script>
</head>
<body>
	<div class="parentBox box1">
		<img src="../images/1-en.jpg" class="pic">
	</div>
	<div class="parentBox box2">
		<img src="../images/2-en.jpg" class="pic">
	</div>
	<div class="parentBox box3">
		<img src="../images/3-en.jpg" class="pic">
	</div>
	<div class="parentBox box4">
		<img src="../images/4-en.jpg" class="pic">
	</div>
	<div class="parentBox box5">
		<img src="../images/5-en.jpg" class="pic">
	</div>
	<div class="parentBox box6">
		<img src="../images/6-en.jpg" class="pic">
	</div>
	<div class="parentBox box7">
		<img src="../images/7-en.jpg" class="pic">
	</div>
</body>
</html>

  

posted @ 2014-09-20 16:17  半颠者  阅读(204)  评论(0编辑  收藏  举报