html页面中图片自适应容器大小且上下左右居中插件

概述

 

做了一个通用的图片自适应插件,方便大家使用,下面直接上代码。

插件源码
// jQuery.imgAutoSize.js
// Wangbaifeng - http://donglisoft.com/ - MIT Licensed
(function ($) {

    $.fn.imgAutoSize = function () {
        this.each(function () {
            var pwidth = $(this).width();
            var pheight = $(this).height();
            var _img = $(this).find("img");
            var iwidth = _img.width();
            var iheight = _img.height();

            //alert(pwidth + "-" + pheight + "-" + iwidth + "-" + iheight)

            if (pwidth <= iwidth || pheight <= iheight) {
                if (iwidth / pwidth > iheight / pheight) {
                    alert(pwidth);
                    _img.css("width", pwidth).css("height", pwidth / iwidth * iheight);
                    _img.css("margin-top", (pheight - pwidth / iwidth * iheight) / 2 + "px");
                } else {
                    _img.css("width", pheight / iheight * iwidth).css("height", pheight);
                    _img.css("margin-left", (pwidth - pheight / iheight * iwidth) / 2 + "px");
                }
            } else {
                _img.css("margin-left", (pwidth - iwidth) / 2 + "px");
                _img.css("margin-top", (pheight - iheight) / 2 + "px");
            }
        });
    };

})(jQuery);

 

使用

页面代码:

<div class="mytest">
    <ul>
        <li>
            <img src="Images/green.png" />
        </li>
        <li>
            <img src="Images/login.gif" />
        </li>
    </ul>
</div>

 

函数调用:

    <script type="text/javascript">
        $(function () {
            $('.mytest ul li').imgAutoSize();
        });
    </script>

 

注意事项:

     1、".mytest ul li“是图片的容器

     2、li要定义大小,且要加属性overflow:hidden;

转载于:https://www.cnblogs.com/jason819/archive/2012/11/15/2771571.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值