图片预加载获取高度和宽度

经典代码:
var imgLoad = function (url, callback) {
    var img = new Image();
    img.src = url;
    if (img.complete) {
        callback(img.width, img.height);
    } else {
        img.onload = function () {
            callback(img.width, img.height);
            img.onload = null;
        };
    };
};


直接看例子代码: (请看注解)
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="lib/ui/js/jquery.min.js"></script>
</head>
<script>
$(function(){
	
	var img = new Image();
	img.src = "http://www.planeart.cn/demo/imgReady/vistas24.jpg?1324093188902";
	$("#offimg").append(img);
	/***********提前获取图片的高度和宽度***********/
	var width = img.offsetWidth;
	var height = img.offsetHeight;
	var intervalId;
	var getPicture = function(){
		console.log("width:"+width+"  height:"+height);
		if(width != img.offsetWidth && height != img.offsetHeight){
			console.log("actualy"+" width:"+img.offsetWidth+"  height:"+img.offsetHeight);
			$("#offimg").remove();
			clearInterval(intervalId);
		}
	}
	intervalId = setInterval(getPicture,150);
	/**********************/
	/*********判断图片是否读取完毕*************/
	if(img.complete){//是否缓存读取
		console.log("======com======");
		console.log("img.width:"+img.width+"   img.height:"+img.height);
		$("#img").append(img);
	}else{
		img.onload = function(e){//图片加载完毕
			console.log("======load======");
			console.log(e);
			console.log("img.width:"+img.width+"   img.height:"+img.height);
			$("#img").append(img);
		}
	}
	/**********************/
	
});
</script>
<body>
	<div id="img"></div><div id="offimg"></div>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值