<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>图片等比缩放</title> <script src="js/jquery-1.8.3.min.js"></script> </head> <style> img{ 400px; height: 200px; } </style> <body> <img src="img/1.jpg" id="img1" onload="DrawImg(this.id, 730, 454)" /> </body> <script> $(function() { function DrawImg(imgId, boxWidth, boxHeight) { alert(boxWidth); var imgWidth = $("#" + imgId).width(); var imgHeight = $("#" + imgId).height(); //比较imgBox的长宽比与img的长宽比大小 if ((boxWidth / boxHeight) >= (imgWidth / imgHeight)) { //重新设置img的width和height $("#" + imgId).width((boxHeight * imgWidth) / imgHeight); $("#" + imgId).height(boxHeight); //让图片居中显示 var margin = (boxWidth - $("#" + imgId).width()) / 2; $("#" + imgId).css("margin-left", margin); } else { //重新设置img的 width和height $("#" + imgId).width(boxWidth); $("#" + imgId).height((boxWidth * imgHeight) / imgWidth); //让图片居中显示 var margin = (boxHeight - $("#" + imgId).height()) / 2; $("#" + imgId).css("margin-top", margin); } } }) </script> </html>