點擊縮圖後彈出大圖,是網站裡很常見的互動。但使用者螢幕尺寸各異,圖片尺寸也千差萬別,若不做處理,彈出的圖可能超出視窗、被裁切或位置歪掉。本文示範如何實作一個能自動等比例縮放、置中顯示的圖片彈窗。
整個實作由兩部分組成:一是負責「計算縮放後尺寸」的 autoImg 函數,二是負責「彈窗外觀與行為」的 popBox 通用彈窗類。
這個函數接收最大高度、最大寬度與圖片原始寬高,回傳縮放後的新尺寸,核心邏輯是判斷圖片是「高於寬」還是「寬於高」,再據此等比縮放到不超過上限:
/******************** 自動適應的圖片彈窗 ********************/
var autoImg=function(argcs){/* 調整圖片大小,等比例縮放
argcs['maxHeight']=>最大高度, argcs['maxWidth']=>最大寬度,
argcs['height']=>圖片高度, argcs['width']=>圖片寬度 */
var _maxHeight='';
var _maxWidth='';
var _newSize=[];
if(argcs['maxHeight']){ _maxHeight=argcs['maxHeight']; }
if(argcs['maxWidth']){ _maxWidth=argcs['maxWidth']; }
if(!argcs['height']){ throw new Error('height未指定'); }
if(!argcs['width']){ throw new Error('width未指定'); }
if(argcs['height']>argcs['width']||argcs['height']==argcs['width']){// 高度不小於寬度
if(argcs['height']>=_maxHeight){
_newSize['height']=_maxHeight;
_newSize['width']=(_maxHeight/argcs['height'])*argcs['width'];
}else{
_newSize['width']=argcs['width'];
_newSize['height']=argcs['height'];
}
return _newSize;
}
if(argcs['width']>argcs['height']){// 寬度大於高度
if(argcs['width']>=_maxWidth){
_newSize['width']=_maxWidth;
_newSize['height']=(_maxWidth/argcs['width'])*argcs['height'];
}else{
_newSize['width']=argcs['width'];
_newSize['height']=argcs['height'];
}
return _newSize;
}
}
imgBox 負責建立彈窗、顯示載入動畫,並在圖片真正載入完成後,重新計算尺寸與位置再呈現:
var imgBox=function(imgSrc){
var winImg=new popBox({// 圖片彈窗
ID:'imgBox',
bgColor:'#a3c90e',
width:906,
moveHandle:false,
closeButton:false,
height:'auto',
times:250,
lock:true,
content:'',
shadow:true,
position:'center',
displayCallBack:function(){
$('body').append('<img id="loading" src="/template/27/img/loading.gif"/>');
$('img[id=loading]').css('z-index',110000).css({position:'absolute',left:$(window).scrollLeft()+($(window).width())/2-($('img[id=loading]').width())/2-22,top:$(window).scrollTop()+($(window).height()/2-($('img[id=loading]').width())/2)});
// 圖片預加載,重新調整窗口大小及位置
var img=new Image();
var _imgWidth=0;
var _imgHeight=0;
img.src=imgSrc;// 為 img 對象添加地址
// 圖片加載完成之後
img.onload=function(){
$('img[id=loading]').remove();
_imgWidth=img.width;
_imgHeight=img.height;
var argcs=[];
var winWidth=$(window).width();
argcs['maxHeight']=750;// 最大高度
argcs['maxWidth']=900;// 最大寬度
argcs['height']=_imgHeight;
argcs['width']=_imgWidth;
var newWH=autoImg(argcs);// 獲得縮略後的圖片寬和高
$('#'+winImg.ID).css({width:newWH['width'],height:newWH['height'],top:parseInt($(document).scrollTop())+parseInt(($(window).height()-newWH['height'])/2),left:$(document).scrollLeft()+parseInt(winWidth/2)-parseInt(newWH['width']/2)});
$('#'+winImg.ID).html('<img src="'+img.src+'" width="'+newWH['width']+'" height="'+newWH['height']+'"/>');
$('#'+winImg.ID+'_bg').css('cursor','pointer').click(function(){
winImg.kill();
});
};
},
unDisplayCallBack:function(){},
killCallBack:function(){}
});
winImg.dispaly();
}
popBox 是一個功能完整的彈窗封裝,支援遮罩、拖動、顯示/隱藏動畫、多層 z-index 管理與狀態追蹤等特性。由於程式碼較長,這裡呈現其完整結構供參考:
// 若使用移動功能,請先導入 jQuery 移動 UI 組件
var popBox=function(settings){// 彈窗函數 settings=[]
/******************* 默認值 *****************/
var _shadow=true;// 是否有遮罩
var _closeButton=false;// 關閉按鈕
var _killButton=false;// kill 按鈕
var _moveHandle=false;// 拖動手柄
var _width=650;// 寬
var _bgColor='#FFF';// 背景樣式
var _height='auto';// 高
var _content='沒有內容';// 內容
var _position='center';// 位置
var _lock=true;// 是否鎖定
var _times=500;// 顯示、隱藏的時間
var _displayCallBack=function(){ alert('display'); }
var _unDisplayCallBack=function(){ alert('unDisplay'); }
var _beforeKillCallBack=function(){ alert('beforeKill'); }
var _killCallBack=function(){ alert('kill'); }
/******************* 默認值 *****************/
// 以下依 settings 覆蓋各項默認值(shadow、bgColor、width、height、
// content、position、times、lock、各回調函數等),此處省略重複賦值細節
/******************** 本類內部變量 *****************/
var _this=this;
var _baseZindex=10000;
var _domWidth=$(document).width();
var _domHeight=$(document).height();
/******************** 本類內部變量 *****************/
/******************** 本類私有函數 *****************/
var _getZindex=function(){// 遍歷 body 下含 popBox 的 div,統計數量
var _len=$('body').children('div').length;
var _countDiv=0;
var _divObj=$('body').children('div');
var _reg=/^popBox_/;
for(var i=0;i<_len;i++){
if(_reg.test(_divObj.eq(i).attr('ID'))){
_countDiv+=1;
}
}
return _countDiv;
}
var _getWinZindex=function(){ return _baseZindex+_getZindex()+2; }
var _geWinBgZindex=function(){ return _baseZindex+_getZindex()+1; }
var _renderBg=function(){// 渲染半透明背景
var _winBgZindex=_geWinBgZindex();
$('body').append('<div id="'+_this.ID+'_bg"></div>');
$('#'+_this.ID+'_bg').addClass('popBox_bg').css({height:_domHeight,width:_domWidth,opcity:0}).css('z-index',_winBgZindex).fadeTo(_times,0.7);
}
var _creatWin=function(){// 創建窗體
$('body').append('<div id="'+_this.ID+'"></div>');
_renderContent(_content);
_initWin();
}
var _initWin=function(){// 初始化窗體
var _winZindex=_getWinZindex();
var _transHeight=0;
if(_height=='auto'){ _transHeight='auto'; }
else{ _transHeight=parseInt(_height)+'px'; }
$('#'+_this.ID).css({width:parseInt(_width)+'px',height:_transHeight,position:'absolute',opticity:1.0,background:_bgColor}).css('z-index',_winZindex);
_locationWin();
}
var _locationWin=function(){// 為窗體定位(置中)
var _windowWidth=parseInt($(window).width());
var _left=(_windowWidth-parseInt(_width))/2;
var _top=parseInt($(document).scrollTop())+parseInt(($(window).height()-$('#'+_this.ID).height())/2);
$('#'+_this.ID).css({top:_top+'px',left:_left+'px'});
}
var _renderContent=function(content){ $('#'+_this.ID).append(content); }
var bindEvent=function(){// 綁定事件
if(_this.status!=='kill'&&_this.status!=='init'){
if(_closeButton!==undefined&&_closeButton!==' '&&_closeButton!==false){
$('#'+_this.ID+' '+_closeButton).css('cursor','pointer').live('click',function(e){ _this.unDisplay(); });
}
if(_killButton!==undefined&&_killButton!==' '&&_killButton!==false){
$('#'+_this.ID+' '+_killButton).css('cursor','pointer').live('click',function(e){ _this.kill(); });
}
}
if(_lock==false){ $('#'+_this.ID).draggable({cancel:''}); }
}
/******************** 本類私有函數 *****************/
/********************** 本類公有函數 ****************/
this.status='init';// init / display / undisplay / kill
this.ID='';
var _ID=settings['ID'];
if(_ID==' '||(typeof _ID)==undefined){ throw new Error('ID不能為空'); }
else{ this.ID='popBox_'+_ID; }
this.display=function(){// 顯示
if(_this.status=='init'||_this.status=='kill'){
_creatWin();
if(_shadow==true){ _renderBg(); }
_this.status='display';
_displayCallBack();
}else{
$('#'+_this.ID).fadeIn(_times);
if(_shadow==true){ $('#'+_this.ID+'_bg').fadeIn(_times); }
_this.status='display';
}
bindEvent();
}
this.kill=function(){// 徹底移除
if(_this.status=='kill'||_this.status=='init'){ throw new Error('非法操作,當前狀態不允許kill'); }
if(_beforeKillCallBack!=undefined){ _beforeKillCallBack(); }
$('#'+_this.ID).remove();
if(_shadow==true){ $('#'+_this.ID+'_bg').remove(); }
_this.status='kill';
if(_killCallBack!=undefined){ _killCallBack(); }
}
this.unDisplay=function(){// 隱藏
if(_this.status=='init'||_this.status=='kill'){ throw new Error('非法操作,當前狀態不允許undisplay'); }
if(_unDisplayCallBack!=undefined){ _unDisplayCallBack(); }
$('#'+_this.ID).fadeOut(_times);
$('#'+_this.ID+'_bg').fadeOut(_times);
_this.status='undisplay';
}
/********************** 本類公有函數 ****************/
}// popBox 網頁彈窗
整体來說,autoImg 負責「算」,popBox 負責「裝」,imgBox 則把兩者串接起來:先顯示載入動畫,等 Image 物件 onload 後取得真實尺寸,交給 autoImg 算出符合視窗的縮放尺寸,最後再調整彈窗的大小與置中位置。這樣一來,無論圖片多大、螢幕多寬,彈窗都能呈現得恰到好處。值得一提的是,popBox 透過狀態機(init / display / undisplay / kill)嚴格管理生命週期,並對非法操作拋出錯誤,這是很值得借鏡的封裝思路。