<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>图片自动按比例缩小代码(防止页面被图片撑破)</title> </head> <body> <div id=article><img height="800" alt="" width="1280" src="picture/08.jpg" /></div> <script type="text/javascript" >
//缩放图片到合适大小 function ResizeImages() { var myimg,oldwidth,oldheight; var maxwidth=150; var maxheight=180 var imgs = document.getElementById('article').getElementsByTagName('img'); //如果你定义的id不是article,请修改此处
for(i=0;i<imgs.length;i++){ myimg = imgs[i];
if(myimg.width > myimg.height) { if(myimg.width > maxwidth) { oldwidth = myimg.width; myimg.height = myimg.height * (maxwidth/oldwidth); myimg.width = maxwidth; } }else{ if(myimg.height > maxheight) { oldheight = myimg.height; myimg.width = myimg.width * (maxheight/oldheight); myimg.height = maxheight; } } } } //缩放图片到合适大小 ResizeImages(); </script> </body> </html> |