解决图片在指定大小盒子内不超出正好填满的代码

<script type="text/javascript">
        $(".img").each(function(i){
            var img = $(this);
            var realWidth;//真实的宽度
            var realHeight;//真实的高度
            //这里做下说明,$("<img/>")这里是创建一个临时的img标签,类似js创建一个new Image()对象!
            $("<img/>").attr("src", $(img).attr("src")).load(function() {
            /*
            如果要获取图片的真实的宽度和高度有三点必须注意
            1、需要创建一个image对象:如这里的$("<img/>")
            2、指定图片的src路径
            3、一定要在图片加载完成后执行如.load()函数里执行
            */
            realWidth = this.width;
            realHeight = this.height;
            //如果真实的宽度大于浏览器的宽度就按照100%显示
            if(realWidth/realHeight > 282/240){
                $(img).css("width","100%").css("height","auto");
            }else{
                $(img).css("height","100%").css("width","auto");
            }
            });
        });
</script>
原文地址:https://www.cnblogs.com/lixihuan/p/7667327.html