函数代码:
function loadpic(ImgObj,width,height){
//获取容器比例
var rates = width/height;
//加载图片
var image = new Image();
image.src = ImgObj.src;
image.onload = function() {
var imgWidth = image.width;
var imgHeight = image.height;
//获取原始图片比例
var rate = imgWidth/imgHeight;
if(rate >= rates){
ImgObj.width = width
ImgObj.height = width/rate
}
else if(rate < rates){
ImgObj.height = height
ImgObj.width = height*rates
}
}
}
函数调用:
loadpic(document.getElementById("容器id"),容器宽度,容器高度);