日期:2014-05-16  浏览次数:20296 次

怎么在页面中根据图片宽度控制图片的宽度
一个页面上要加载很多图片,这些图片的原始宽度未知。现在要实现的是:图片宽度小于某个值时以原始宽度显示,大于某个值是以该值作为图片宽度进行显示。
我试过用图片的onLoad()事件,这个方法不是很可靠,在图片未加载完成的情况下就无效,还有没有其他方法?

------解决方案--------------------
在img 标签中加入 onload 事件
------解决方案--------------------
先使用Image对象预装载图片
通过Image对象的height和width属性得到图片的高度和宽度
并设置img的宽度即可
------解决方案--------------------
<!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 ">
<!-- DW6 -->
<head>
<meta http-equiv= "Content-Type " content= "text/html; charset=utf-8 " />
<title> shawl.qiu template </title>
<script type= "text/javascript ">
// <![CDATA[
window.onload=function(){
fResizeImg(400, 300, 'table ');
//fResizeImg(500, 500);
}
/*------------------------------------------------------*\
* Subject: 使用 javascript 函数 完美控制页面图片显示大小 By shawl.qiu
* 使用:
* --------------------------------------
* 1. Javascript 脚本块
* window.onload=function(){
* fResizeImg(500, 500, 'img ');
* //fResizeImg(500, 500);
* }
*
* 2. html body 标签
* <body onload= "fResizeImg(500, 500, 'textMain '); " >
* --------------------------------------
* 注: 必须在页面加载完毕后使用本函数(这是基本的客户端应用概念)
* --------------------------------------
* 参数说明:
* nWidth: 数值, 设置最大宽度, 图片宽度大于该值则设置大小为该值
* nHeight: 数值, 设置最大高度, 图片高度大于该值则设置大小为该值
* sId: 字串, 设置函数作用域 ID, 如不设置, 作用于全页面.
\*-------------------------------------------------------*/
//-----------------------------begin function fResizeImg(nWidth, nHeight, sId)-------------------------//
function fResizeImg(nWidth, nHeight, sId){
var oImg, oRange;
if(!sId)oRange=document.images;
else oRange=document.getElementById(sId).getElementsByTagName( 'img ');

for(var i=0; i <oRange.length; i++){
oImg=oRange[i];
if(oImg.width> nWidth&&(oImg.height <oImg.width)){
oImg.height=oImg.height-(oImg.height/(oImg.width/(oImg.width-nWidth)))
oImg.width=nWidth;
}else if(oImg.height> nHeight&&(oImg.height> oImg.width)){
oImg.width=oImg.width-(oImg.width/(oImg.height/(oImg.height-nHeight)))
oImg.height=nHeight;
}
oImg.onclick=function(){
try{ w.close();} catch(e){}
var oTemp=new Image();
oTemp.src=this.src;
var nWinWidth=oTemp.width;
var nWinHeight=oTemp.height;
oTemp=null;
w=open( '# ', 'imgurl ', 'width= '+nWinWidth+ ', height= '+nWinHeight+
', left= '+(screen.availWidth-nWinWidth)/2+ ', top= '+(screen.availHeight-nWinHeight)/2);
w.document.write( ' <script> document.onclick=function(){ close();} <\/script> ');
w.document.write( ' <img src= " '+this.src+ ' "/> ',
' <style> body{margin:0; padding:0;} <\/style> ');
w.focus();
w.document.close();
return true;
}
} // shawl.qiu script
return true;
}
//-----------------------------end function fResizeImg(nWidth, nHeight, sId)---------------------------//
//]]>
</script>
</head>
<body>
<table width= "100% " border= "1 " id= "table