JS图片加载完毕事件 & 图片等比缩放 兼容全部浏览器

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);
			}
		}

	})
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值