jQuery制作图片的等比例缩放

1资料的排版

2.html代码

1 <body>
2 <div class="BB"><img src="dw.jpg"  alt="动物" onload="setPic($(this))"/></div>
3 <div class="BB"><img src="dw1.jpg"  alt="动物" onload="setPic($(this))"/></div>
4 <div class="BB"><img src="yy.jpg" alt="人" onload="setPic($(this))" /></div>
5 </body>

3.css代码

<style type="text/css">
    .BB{ width:100px; height:80px; border:1px solid red; overflow:hidden; margin-top:10px; float:left; margin-left:10px; text-align:center; line-height:100px; position:relative;}
    img{position:relative;}
    </style>

4.js代码

<script src="jquery-1.7.2.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        var BNImg = {
            iconW: 100,
            iconH: 80,
            getOriginPicWandH: function (imgObj) {
                return {  imgObj.width(), height: imgObj.heght() };
            },
            setPicWandH: function (imgObj) {
                var originW = imgObj.width();
                var originH = imgObj.height();
                var maxWorH = originW >= originH ? { w: originW} : { h: originH };
                var originRate = originW / originH;
                if (maxWorH.w) {
                    imgObj.width(BNImg.iconW);
                    var newH = BNImg.iconW / originRate
                    imgObj.height(newH);
                    var top = (BNImg.iconH - newH) / 2;
                    imgObj.css("top",top+"px");
                }
                else if (maxWorH.h) {
                    imgObj.height(BNImg.iconH);
                    imgObj.width(originRate * BNImg.iconH);
                }
            }
        };        
        function setPic(obj) {
            BNImg.setPicWandH(obj);
         }
原文地址:https://www.cnblogs.com/guoyansi19900907/p/3274773.html