码迷,mamicode.com
首页 > Web开发 > 详细

js实现图片的大小自适应效果

时间:2016-12-29 13:17:54      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:contain   blog   rmq   code   box   sid   pen   pre   ima   

需求是传过来一个图片,根据外层div的大小自动进行缩放效果。

function ShowSecondImg(v) {
    var rate, newX, newY,newW, newH = 0;   //表示图片相对窗口的缩放比例
    var imgW, imgH;
    var centerW = $(window).width() - $("#alarmQueue").width() - $("#presInfo").width() - 40;

    var centerH = $(window).height() - $("#detailedInfor").height()-148;
    $("#imgBoxs").find("#second").remove();
    var img = $(‘<img/>‘, { src: v.First_frame_image_url, "id": "second" });//v.First_frame_image_url

    img.prependTo(‘#imgBoxs‘);

    imgW = img.width();
    imgH = img.height();
    //获取的参数
    var rectX= parseInt(v.facerect.x);
    var rectY =parseInt(v.facerect.y);
    var rectWidth =parseInt(v.facerect.w);
    var rectHeight =parseInt(v.facerect.h);
    // alert(v.facerect.x);

    //var i = (centerW / 16 - centerH / 9) > 0 ? 0 : 1;
    var i= (centerW/centerH - imgW/imgH ) > 0 ? 0 : 1;
    if (i == 1) {
        //如果窗口宽不长,高长。以宽为准。
        rate = imgW / centerW;
        var imgRateH = imgH / rate;  //img real rate height;
        newX = rectX / rate
        newY = rectY / rate;
        newW = rectWidth / rate;
        newH = rectHeight / rate;

        $("#imgBox").width(centerW);
        $("#imgBox").css("height", "100%");
        $("#second").css({ "width": centerW, "height": imgRateH });
    }
    else if (i == 0) {
        //如果窗口宽足够长,高不长。以高为准。
        rate = centerH / imgH;
        var imgRateW = imgW * rate;  //img real rate width;
        var leftsideW = (centerW - imgRateW) / 2;    //leftside add rightside  width;
        newX = rectX * rate + leftsideW;
        newY = rectY * rate;
        newW = rectWidth * rate;
        newH = rectHeight * rate;

        $("#imgBox").height(centerH);
        $("#imgBox").css("width", "100%");
        $("#second").css({ "width": imgRateW, "height": centerH });

    }
    // $("#detailedInfor").height($(".container").height()-centerH);
    $("#faceDiv").attr(‘style‘, ‘display:block;top:‘ + newY + ‘px;left:‘ + newX + ‘px;width:‘ + newW + ‘px;height:‘ + newH + ‘px‘);

}

 

js实现图片的大小自适应效果

标签:contain   blog   rmq   code   box   sid   pen   pre   ima   

原文地址:http://www.cnblogs.com/pengpenglin/p/6232261.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!