动态计算图片宽高适配

前几天接了个需求,要求把扫描的影像展示出来,由于客户的纸张文件·大小不固定,而产品又要求图片不能失真,因此自己捣鼓了个小方法代码如下:

function adaptImg(el, maxHeight) { //el 是图片的id  
            var textId = document.getElementById(el),
                computedWidth = textId.clientWidth, //初始设置的宽度
                height = textId.naturalHeight, //只支持ie9+
                width = textId.naturalWidth,
                imgScale = (width / height).toFixed(2); //图片的宽高比
            if (computedWidth / imgScale > maxHeight) { //如果图片的宽度100% 计算出的高度大于最大值 则以高度适配 
                textId.style.width = maxHeight * imgScale + "px"; //图片的高度设置为最大值 计算宽度
            }
        }

 

posted @ 2018-06-19 10:37  秋月渔舟  阅读(1726)  评论(0编辑  收藏  举报