美文网首页
图片在盒子中保持宽高比不变

图片在盒子中保持宽高比不变

作者: 何大必 | 来源:发表于2018-08-20 20:30 被阅读0次

    上代码

    //CSS
    <style>
    .imgWrap{
                position: relative;
                width: 300px;
                height: 300px;
                margin: 20px;
                border:1px solid red;
            }
            .imgWrap img{
                position: absolute;
            }
    </style>
    //HTML
    <body>
    <div class="imgWrap">
        <img src="images/01.jpg" alt="">
    </div>
    <div class="imgWrap">
        <img src="images/02.jpg" alt="">
    </div>
    </body>
    //JS
    $(function () {
            $(".imgWrap img").each(function () {
                adjustImg($(this),$(this).parents(".imgWrap"));
            })
        });
    function adjustImg($this,$box) {
                //图片宽高
                var imgW=$this.width();
                var imgH=$this.height();
                //盒子宽高
                var boxW=$box.width();
                var boxH=$box.height();
                //求比例最小值
                var min=Math.min(boxW/imgW,boxH/imgH,1);
                var offsetLeft=(boxW-(min*imgW))/2;
                var offsetTop=(boxH-(min*imgH))/2;
                $this.css({
                    width:min*imgW,
                    height:min*imgH,
                    left:offsetLeft,
                    top:offsetTop
                })
        }
    

    效果:

    image.png
    image.png

    记于8月20日。

    相关文章

      网友评论

          本文标题:图片在盒子中保持宽高比不变

          本文链接:https://www.haomeiwen.com/subject/bffriftx.html