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

关于js中this所指代元素的问题
JScript code
<!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" />
    <script type="text/javascript" src="jquery-1.8.1.js"></script>
<script type="text/javascript">
var flag=false;
function DrawImage(ImgD,imageWidth,imageHeight) {
   var image=new Image();

   image.src=ImgD.src;
    console.log(image.src);//输出“file:///D:/WebStorm%20WorkSpace/test5/undefined”
   if(image.width>0 && image.height>0){
    flag=true;
    if(image.width/image.height>= imageWidth/imageHeight){
     if(image.width>imageWidth){
     ImgD.width=imageWidth;
     ImgD.height=(image.height*imageWidth)/image.width;
     }else{
     ImgD.width=image.width;
     ImgD.height=image.height;
     }
     }
    else{
     if(image.height>imageHeight){
     ImgD.height=imageHeight;
     ImgD.width=(image.width*imageHeight)/image.height;
     }else{
     ImgD.width=image.width;
     ImgD.height=image.height;
     }
     }
    }
  }

   $("#pic").ready(function(){
       DrawImage(this,150,130);//图片大小没有改变,为什么?

   })
 


</script>
<title>Anddecor</title>
</head>
<body>

<img alt="" src="img/ipad.jpg" id="pic"/>/*定义图片宽不超过150,高不超过130*/
</body>
</html>


以上代码是从网上找来的一段关于图片自适应DIV的代码,自己修改了一下,想让图片载入完成后自动修改大小,可是没有效果,前辈们帮忙看看这个该怎么改。

原始代码如下:
JScript code
<!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" />
<script type="text/javascript">
var flag=false;
function DrawImage(ImgD,imageWidth,imageHeight) {
   var image=new Image();
   image.src=ImgD.src;
   if(image.width>0 && image.height>0){
    flag=true;
    if(image.width/image.height>= imageWidth/imageHeight){
     if(image.width>imageWidth){
     ImgD.width=imageWidth;
     ImgD.height=(image.height*imageWidth)/image.width;
     }else{
     ImgD.width=image.width;
     ImgD.height=image.height;
     }
     }
    else{
     if(image.height>imageHeight){
     ImgD.height=imageHeight;
     ImgD.width=(image.width*imageHeight)/image.height;
     }else{
     ImgD.width=image.width;
     ImgD.height=image.height;
     }
     }
    }
  }
 


</script>
<title>Anddecor</title>
</head>
<body>

<img alt="" src="img/ipad.jpg" onload= "javascript:DrawImage(this,150,130)" />/*定义图片宽不超过150,高不超过130*/
</body>
</html>


------解决方案--------------------
第一:jQuery中好像并没有使用$("#pic").ready([fn])这种方法来确实图片是否已经加载完成的用法
第二:你可以在onload事件中进行相关的绑定
JScript code
window.onload=function(){
    var img=document.getElementById("pic");
    DrawImage(img,150,130);
}