js脚本按比例缩放图片

来源:互联网 发布:淘宝卖鞋正品的店铺 编辑:程序博客网 时间:2024/04/30 09:38

    在前端开发过程中 总会遇到UI提供的图片尺寸比例不对的情况  数量比较大的时候处理起来非常的麻烦,这时候可以写一个脚本来批量处理这些图片 具体做法是调整图片容器的尺寸比例 然后让图片刚好填满容器

function ImgPro($imgContainer, w,h) {//imgContainer是图片容器  w,h是要设的比例    var height = $imgContainer.width()/w*h;    $imgContainer.height(height);    var $img = $imgContainer.children('img');    var imgw = $img.width();    var imgh = $img.height();    var horizontal=$imgContainer.width();    //console.log(imgh);        if (imgh < height||imgw < horizontal) {            if (imgw < horizontal) {                $img.width(horizontal);                $img.height(height);                $img.css('max-width', horizontal + 'px');            }else{                $img.height(height);                var width = imgw * height / imgh;                $img.width(width);                $img.css('max-width', width + 'px');            }        }        else{            $img.width(horizontal);            $img.height(height);        }}
运用例子:
        
$(".div-responsive").each(function(){    ImgPro($(this), 3,2);});
$(window).resize(function(){    $(".div-responsive").each(function(){        ImgPro($(this), 3,2);    });  });
//html 代码 class=“img-responsive”是用到了bootstrap的技术栈
<div class="div-responsive">    <img  class="img-responsive" src="@routes.Assets.at("images/hypoloop.jpg")"></div>
//添加div-responsive
没添加div-responsive

0 0
原创粉丝点击