almost 6 years ago

JQuery Plugin 練習
因為常遇到要對比壓縮圖檔的問題
所以寫個 Plugin 方便使用

/*
 * resize img 物件
 *  範例
 *  <img src="Winter.jpg" />
 *  
 *  $(function (){
 *      $("img").myReImgSize({
 *          reHeight:100,
 *          reWidth:100
 *      });
 *
 *      OR
 *
 *      $("img").myReImgSize();
 *  });
 *  
 *  說明
 * reHeight 壓縮範圍內的高
 * reWidth 壓縮範圍內的寬
 */
$.fn.myReImgSize = function (settings) {
    // 預設屬性
    var _defaultSettings = {
        reHeight: 200,
        reWidth: 200
    }
    
    var _settings = $.extend(_defaultSettings, settings);
    
    var _handler = function () {
        //取得影像實際的長寬
        var imgW = $(this).width();
        var imgH = $(this).height();
        
        //計算縮放比例
        var preW = _settings.reWidth / imgW;
        var preH = _settings.reHeight / imgH;
        
        var pre = 1;
        if (preW > preH) {
          pre = preH;
        } else {
          pre = preW;
        }
        
        //設定目前的縮放比例
        $(this).width(imgW * pre);
        $(this).height(imgH * pre);
    };
    
    return this.each(_handler);
}
← clone Plugin PopUp Plugin →
 
comments powered by Disqus