JS 判断图片图片加载完毕

文章参考 http://www.cnblogs.com/ymy124/p/4538695.html

在工作中遇到这么一个问题 —— 某个图片前后都有空白,大概前面的空白占图片的1/3 ,后面的占图片高度的1/4,为了节省流量,因此想根据图片高度计算前后的留白,因为图片的大小也是自适应的

理论基础:

document.getElementById("img_load").onload = function(){
	//获取图片的高度和宽度
	//console.log(this.width);
	//console.log(this.height);
	var topHeight = this.height/3;
	var bottomHeight = this.height/5;
	$(this).before('<div style="height: '+topHeight+'px"></div>')
	$(this).after('<div style="height: '+bottomHeight+'px"></div>')
};

项目实战:

//guajiangqu_img图片加载完之后执行的方法
guajiangqu_img.onload = function(){
	$(this).css({
		"padding-top":this.height * 0.75 + "px",
		"padding-bottom":this.height * 0.75 + "px"
	});
}

猜你喜欢

转载自hbiao68.iteye.com/blog/2262036