一般用于放大查看商品圖片,在凡客,京東商城,阿里巴巴等都有類似的效果。
好處是能在原圖附近對圖片進行局部放大查看,而且可以通過鼠標控制查看的部位。
前一陣子看到sohighthesky的圖片放大效果,心血來潮自己也寫一個看看。
這個程序有以下特點:
1,支持使用原圖放大或新圖片設置大圖;
2,大圖完成載入前使用原圖放大代替,減少操作等待時間;
3,支持鼠標滾動縮放大圖;
4,可以通過設置顯示范圍或顯示框大小設置顯示尺寸;
5,可以設置是否自動隱藏顯示框;
6,支持插件形式的擴展來實現更多的功能(下一篇再詳細介紹)。
兼容:ie6/7/8, firefox 3.6.2, opera 10.51, safari 4.0.4, chrome 4.1
代碼如下:
var styles;
if ( !viewer.clientWidth ) {
var style = viewer.style;
styles = {
display: style.display,
position: style.position,
visibility: style.visibility
};
$$D.setStyle( viewer, {
display: "block", position: "absolute", visibility: "hidden"
});
}
this._viewerWidth = viewer.clientWidth;
this._viewerHeight = viewer.clientHeight;
if ( styles ) { $$D.setStyle( viewer, styles ); }
rangeWidth = Math.ceil( this._viewerWidth / scale );
rangeHeight = Math.ceil( this._viewerHeight / scale );
注意,顯示范圍是通過clientWidth/clientHeight來獲取的。
如果顯示框是display為none的隱藏狀態,就不能直接獲取clientWidth/clientHeight。
這種情況下,程序用以下方法獲取:
1,記錄display/position/visibility的原始值;
2,分別設為"block"/"absolute"/"hidden",這是既能隱藏也能占位的狀態;
3,獲取參數;
4,重新設回原始值,恢復原來的狀態。
得到顯示范圍后,再配合比例就能得到范圍參數了。
ps:這是通用的獲取不占位元素尺寸參數的方法,jquery的css也是用這個方法獲取width/height的。
比例計算后可能會得到小數,而尺寸大小只能是整數,程序一律使用Math.ceil來取整。
【放大效果】
所有東西都設置好后,就可以執行start設置觸發程序了。
程序會自動執行start方法,里面主要是給原圖對象的mouseover/mousemove綁定_start程序:
var image = this._image, START = this._START;
$$E.addEvent( image, "mouseover", START );
$$E.addEvent( image, "mousemove", START );
分別對應移入原圖對象和在原圖對象上移動的情況。
ps:如果使用attachEvent的話還要注意重復綁定同一函數的問題,這里的addEvent就沒有這個問題。
綁定的_start程序,主要是進行一些事件的解綁和綁定:
代碼如下:
$$E.removeEvent( image, "mouseover", this._START );
$$E.removeEvent( image, "mousemove", this._START );
$$E.addEvent( document, "mousemove", this._MOVE );
$$E.addEvent( document, "mouseout", this._OUT );