2010-05-11 56 views
4

我有一些缩略图,当你点击它们时,我有一个带有DIV的模式框,我想从更大的图像中缩放50%w/h。
我想知道如果缩放下面的方法是800x530px的图像有效和跨浏览器:使用jQuery加载完毕后的缩放图像

#foo-img { width: 100%; height: 100%; } 
#foo-div { 
    width: 400px; height: 265px; 
    padding: 10px; background: black; 
} 

<div id="foo-div"> 
    <img id="foo-img" src="img/003.jpg" /> 
</div> 

我似乎无法只设置#富-IMG W/H在属性每次我加载一张新图像时,它都会减小50%! 下面是一些作品,但似乎非常多的代码,我..

 var rnd = Math.floor(Math.random() * 101) 

     $("a.loadimg").click(function() { 
      // resets the DIV 
      imgLoadReset(); 
      var imgPath = "images/" + $(this).text() + "?" + rnd; 
      imgLoad(imgPath); 
      return false; 
     }); 

     function imgLoad(imgPath) { 
      $("#foo-img").hide() 
      .one('load', function() { 
       imgLoadComplete(); 
      }) 
      .attr("src", imgPath) 
      .each(function() { 
       if(this.complete) $(this).trigger('load'); 
      }); 
     }   

     function imgLoadComplete() { 
      // after the image is completely loaded, we can get the w/h of the image 
      var imgW = $("#foo-img").width()/2; 
      var imgH = $("#foo-img").height()/2; 

      // set div to half image size   
      $("#foo-div").css({ "width": imgW, "height": imgH }); 
      // this should scale the image inside the div 
      $("#foo-img").css({ "width": "100%", "height": "100%" }); 

      $("#foo-img").show(); 
     } 

     function imgLoadReset() { 
      // delete w/h attributes otherwise it doesn't work 
      $("#foo-img").css({ "width": "", "height": "" }); 
      // clear image with a blank 
      $("#foo-img").attr("src", "about:blank"); 
     } 

HTML

<div id="foo-div"> 
    <img id="foo-img" src="about:blank" /> 
</div> 
<hr> 
<a class="loadimg" href="#">001.jpg</a> | 
<a class="loadimg" href="#">002.jpg</a> | 
<a class="loadimg" href="#">003.jpg</a> | 
<a class="loadimg" href="#">004.jpg</a> 

回答

1

使用

img { 
    max-width: 100%; 
    width: auto; 
    height: auto; 
} 

为你的形象;指定他们的容器div的所需宽度(以像素为单位)。