<!DOCTYPE html> <html lang="zh-cn"> <head> <meta charset="UTF-8"> <title>缩放图片到合适的大小</title> </head> <body> <div id="article"> <p> <img src="http://www.lanrentuku.com/down/js/images/12498880470.jpg" width="1280" height="800" alt=""> </p> <p> <img src="http://www.pp3.cn/uploads/201608/201608299.jpg" width="1057" height="661" alt=""> </p> </div> <script> var myImg, oldWidth, oldHeight; var maxWidth = 550; var maxHeight = 888; var imgs = document.getElementById('article').getElementsByTagName('img') function resizeImage() { for(var i = 0;i < imgs.length;i++) { myImg = imgs[i]; oldWidth = myImg.width; oldHeight = myImg.height; //console.log('' + oldWidth + ', height:' + oldHeight); if (oldWidth >= oldHeight) { if (oldWidth > maxWidth) { myImg.width = maxWidth; myImg.height = oldHeight * (maxWidth / oldWidth); }; } else if (oldWidth < oldHeight) { if(oldHeight > maxHeight) { myImg.height = maxHeight; myImg.width = oldWidth * (maxHeight / oldHeight); } } } } // 缩放图片到合适的大小 resizeImage() </script> </body> </html>