测试图片居中显示_新_3中情况
测试图片居中展示_新_3中情况
var imgCenterUi = { init : function(arg){ var _rule = arg.rule || 1; var _isTrue = arg.isTrue || false; var thisImgHeight,thisImgWidth,parConHeight,parConWidth,scale,parscale = ''; if(!_isTrue){ var parObj = $('#'+arg.parId); var thisObj = parObj.find('img'); policy(thisObj); }else{ $('img').each(function(e) { policy($(this)); }); } function policy(_thisObj){ var _thisObj = _thisObj thisImgHeight = _thisObj.height(); thisImgWidth = _thisObj.width(); _thisObj.parent().css({'position':'relative','overflow':'hidden'});//此段应该在css里边早就设置过的 parConHeight = _thisObj.parent().height(); parConWidth = _thisObj.parent().width(); parscale = parConWidth/parConHeight;//计算容器宽度跟高度的比例 scale = thisImgWidth/thisImgHeight;//计算当前图片宽度跟高度的比例 if(_rule == 1){ imgCenterUi.bespread(thisImgHeight,thisImgWidth,parConHeight,parConWidth,scale,parscale,_thisObj); } if(_rule == 2){ imgCenterUi.half_bespread(thisImgHeight,thisImgWidth,parConHeight,parConWidth,scale,parscale,_thisObj); } if(_rule == 3){ imgCenterUi.centerImg(thisImgHeight,thisImgWidth,_thisObj); } } }, /* @铺满 */ bespread : function(thisImgHeight,thisImgWidth,parConHeight,parConWidth,scale,parscale,thisObj){ var _thisObj = thisObj; if(scale > parscale){ margLeft = thisImgWidth/(thisImgHeight/parConHeight); _thisObj.css({'height':parConHeight,'position':'relative','left':'50%','margin-left':'-'+margLeft/2+'px'}); }else{ margTop = thisImgHeight/(thisImgWidth/parConWidth); _thisObj.css({'width':parConWidth,'position':'relative','top':'50%','margin-top':'-'+ margTop/2 +'px'}); } return false; }, /* @一半铺满 */ half_bespread : function(thisImgHeight,thisImgWidth,parConHeight,parConWidth,scale,parscale,thisObj){ var _thisObj = thisObj; if(scale > parscale){ margTop = thisImgHeight/(thisImgWidth/parConWidth); _thisObj.css({'width':parConWidth,'position':'relative','top':'50%','margin-top':'-'+ margTop/2 +'px'}); }else{ margLeft = thisImgWidth/(thisImgHeight/parConHeight); _thisObj.css({'height':parConHeight,'position':'relative','left':'50%','margin-left':'-'+margLeft/2+'px'}); } return false; }, /* @仅仅居中展示、多余的部分隐藏、隐藏的部分应该是在css里边就做好、设置超出父容器的部分隐藏就好 */ centerImg : function(thisImgHeight,thisImgWidth,thisObj){ var _thisObj = thisObj; _thisObj.css({'position':'absolute','left':'50%','top':'50%','margin-left':'-'+(thisImgWidth/2)+'px','margin-top':'-'+(thisImgHeight/2)+'px'}); return false; } } $(function(){ //需要两个参数、 arg = { rule:'1',//1全屏铺满不变形 2.一面铺满不变形 3.保持原形居中展示 isTrue:false,//是否对所有img进行统一设置 parId:'img'//如果只对某一个img处理那么需要传入他父容器的ID }; arg2 = { rule:'2',//1全屏铺满不变形 2.一面铺满不变形 3.保持原形居中展示 isTrue:false,//是否对所有img进行统一设置 parId:'img2'//如果只对某一个img处理那么需要传入他父容器的ID }; arg3 = { rule:'3',//1全屏铺满不变形 2.一面铺满不变形 3.保持原形居中展示 isTrue:false,//是否对所有img进行统一设置 parId:'img3'//如果只对某一个img处理那么需要传入他父容器的ID }; imgCenterUi.init(arg); imgCenterUi.init(arg2); imgCenterUi.init(arg3); /* 如果需要将所有的图片都按照一种格式、如下: arg = { rule:'1',//1全屏铺满不变形 2.一面铺满不变形 3.保持原形居中展示 isTrue:true }; imgCenterUi.init(arg); */ });