放一段图片自定义大小调整的代码(jQuery插件)

来源:互联网 发布:js点击超链接弹出窗口 编辑:程序博客网 时间:2024/05/18 15:28

在网上搜索了一些这样的代码,都写了好多,不想用那些网上的代码,自己写了一个处理,感觉挺简单的,供大家做个参考吧:

/* jQuery resizeImage Plugin++
*
* Version 1.01
*
* create by collonn@126.com 2011-03-10
*
* Usage: $('.img').resizeImage( {'maxWidth':360, 'maxHeight':200});
*
* Defaults:
* id : the note that you binded
* maxWidth: max width
* maxHeight: max height
* isIE6: is ie6
*/
(function($) {
   
    jQuery.fn.resizeImage = function(options){
        defaults = {
            id: '#' + $(this).attr('id'),
            maxWidth:100,
            maxHeight:100,
            isIE6: $.browser.msie && parseInt($.browser.version) <= 8 ? true : false
        };
       
        jQuery.extend(defaults,options);
       
        //取当前image的width和height
        var curWidth = parseInt($(this).attr('width'));
        var curHeight = parseInt($(this).attr('height'));
        var pw = curWidth/defaults.maxWidth;
        var ph = curHeight/defaults.maxHeight;
       
        //以百分比大小做度量
        if(pw <= 1 && ph <= 1){
            return;
        }
       
        //很宽的情况
        if(pw > ph){
            $(this).attr({
                'width': defaults.maxWidth,
                'height': parseInt(curHeight * (defaults.maxWidth/curWidth))
            });
        }else{//很高的情况
            $(this).attr({
                'width': parseInt(curWidth * (defaults.maxHeight/curHeight)),
                'height': defaults.maxHeight
            });
        }
    };
   
})(jQuery);

原创粉丝点击