angular 图片处理相关指令



//添加背景图片
    app.directive('setGround', function() { 
	    return {
	      	restrict:'AE',//定义范围
	     	transclude: false,
	     	replace: true,
	      	scope: {
	        	ground: "@",   // ground 值传递 (字符串,单向绑定)
	        },
	        link:function(scope, element, attrs){
	        	//错误图片和加载图片
	        	var errImg = 'img/404/404.png';
	        	var loadingImg = 'img/loading/loading3.gif';

	        	//监听属性值的变化,为空会进一次 有值又会进一次
		        attrs.$observe('ground', function (value) {
		        	var backGroundImg = element[0];
		        	if(value){
		        		//用来判断两秒后 图片地址是否还是空的
		        		scope.value = value;
		        		//有值先当有效地址处理,保证图片快速显示
				        setBackgrund(backGroundImg,value);
			        	/*判断图片地址是否有效,无效一秒后换成404图片*/
				        var img=new Image();
			            img.src=value;
			            setTimeout(function(){
				            if(img.fileSize > 0 || (img.width > 0 && img.height > 0)){
				            	console.log("图片正确")
				            }else{
						        setBackgrund(backGroundImg,errImg);
				            }
			            },1000);
		        	}else{
		        		//图片地址为空,设置加载中图片
				        setBackgrund(backGroundImg,loadingImg);

		        		//两秒后重新检测图片,为空就设置404图片,有值不作处理 上面会处理
		        		setTimeout(function(){
		        			if(!scope.value){
		        				//设置404图片
						        setBackgrund(backGroundImg,errImg);
		        			}
		        		},2000);
		        	}
			    });	
			    function setBackgrund(backGroundImg,value){
			        backGroundImg.style.background="url("+value+") center no-repeat";
			        backGroundImg.style.backgroundSize="cover";
			    }
	        }
	    }
    });

/** 图片加载失败默认图片指令*/
	app.directive('whenerror', function(){
		// Runs during compile
		return {
			link: function($scope, iElm, iAttrs, controller) {
				//图片数据为空时
				if(!iAttrs['src']){
					changeSrc(iElm,iAttrs);
				}
				//图片数据不为空,但是无法访问时
				var retryTimes = 0;
				iElm.on('error', function(){
					retryTimes++;
					if(retryTimes>=2){
						return;
					}
					changeSrc(iElm,iAttrs);
				})
				function changeSrc(iElm,iAttrs){
					if(iAttrs['whenerror']=='small'){
						iElm[0].src='img/404/4041.png'
					}else if(iAttrs['whenerror']=='big'){
						iElm[0].src='img/404/4042.png'
					}else if(iAttrs['whenerror']=='homebig'){
						iElm[0].src='img/imgs/homepage-sm.png'
					}else{
						iElm[0].src='img/404/404.png'
					}
				}
			}
		};
	});

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值