var img = new Image();
img.src = =$('img').attr("src");
if(img.complete){
loadpic();
}else{
img.onload = loadpic;
}
function loadpic(){
//图片加载完毕
}
试了很多方式,这种方式兼容全部浏览器
等比缩放,需要JQ,可适应缩放也可撑满缩放2种方式:
//等比缩放居中 url: www.flashme.cn 2016-11-15
//图片居中
function imgCenter(obj,full,mar_x,mar_y){
obj.each(function(){
var $this=$(this);
if(full==undefined){full=2}
var img = new Image();//创建缓存临时img
img.src = $this.attr("src");
if(img.complete){
loadpic();
}else{
img.onload = loadpic;
}
function loadpic(){
var objHeight=img.height;//图片原始高度
var objWidth=img.width;//图片原始宽度
var parentHeight=$this.parent().height();//图片父容器高度
var parentWidth=$this.parent().width();//图片父容器宽度
var NewWidth = parentHeight / objHeight * objWidth;
//大于既撑满裁切缩放,小于既全显缩放
if (NewWidth > parentWidth && full==1) {
$this.attr("width",NewWidth);
$this.attr("height",parentHeight);
} else if (NewWidth < parentWidth && full==2) {
$this.attr("width",NewWidth);
$this.attr("height",parentHeight);
}else {
$this.attr("width",parentWidth);
$this.attr("height",parentWidth / objWidth * objHeight);
}
if(mar_x=="left"){
$this.css("margin-left",0);
}else if (mar_x=="right") {
$this.css("margin-right",0);
}else{
$this.css("margin-left",(parentWidth - $this.width())*0.5);
}
if(mar_y=="top"){
$this.css("margin-top",0);
}else if (mar_y=="bottom") {
$this.css("margin-bottom",0);
}else{
$this.css("margin-top",(parentHeight - $this.height())*0.5);
}
}
})
}