前幾天接了個需求,要求把掃描的影像展示出來,由於客戶的紙張文件·大小不固定,而產品又要求圖片不能失真,因此自己搗鼓了個小方法代碼如下:
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"; //圖片的高度設置為最大值 計算寬度 } }