almost 6 years ago

img 的遮罩 Plugin
蠻常用到的....寫一下
可設定圓角

/*
 * 遮罩 img 物件
 *  範例
 *  <img src="Winter.jpg" />
 *  
 *  $(function (){
 *      $("img").myRectImg({
 *          rectHeight: 300,
 *          rectWidth: 300,
 *          rectRadius: 30,
 *          callback: function(data) {
 *              data.css({"border-style" : "dashed", "border-width": 1});
 *          }
 *      });
 *  });
 *  
 *  說明
 * rectHeight 遮罩的高
 * rectWidth 遮罩的寬
 * isInlineBlock  display 是否設定為 inline-block
 * borderWidth 遮罩框線寬度
 * callback 回傳 data 為遮罩的物件, 可自行修改css
 */
$.fn.myRectImg = function (settings) {
    // 預設屬性
    var _defaultSettings = {
        rectHeight: 200,
        rectWidth: 200,
        isInlineBlock:true,
        rectRadius: 0,
        borderWidth: 0,
        callback: function(data){}
    }
    
    var _settings = $.extend(_defaultSettings, settings);
    
    var _handler = function () {
        // 計算浮動位置
        var imgW = $(this).width();
        var imgH = $(this).height();
        
        var imgTop = (_settings.rectHeight - imgH) / 2;
        var imgLeft = (_settings.rectWidth - imgW) / 2;
        
        var rectDiv = $("<div></div>");
        
        $(this).wrap(
            // 加入遮罩 
                rectDiv.css({
                "position" : "relative",
                "overflow" : "hidden",
                "width" : _settings.rectWidth,
                "height" : _settings.rectHeight,
                "display" : (_settings.isInlineBlock) ? "inline-block" : "block",
                "border-radius": _settings.rectRadius,
                "border-style" : "solid",
                "border-width" : _settings.borderWidth
            })
        
        ).css({"top" : imgTop, "left" : imgLeft, "position" : "absolute"});
        
        _settings.callback($(this).parent("div"));
    }
    
    return this.each(_handler);
}
← PopUp Plugin Html 注解 與 POST 問題 →
 
comments powered by Disqus