2010-05-11 5 views
4

J'ai quelques vignettes et quand vous cliquez dessus, j'ai une boîte Modal avec un DIV que je veux mettre à l'échelle 50% w/h de la plus grande image.
Je voudrais savoir si la méthode suivante pour mise à l'échelle est valide et cross-navigateur pour une image de 800x530px:échelle image dans div après charge complète avec 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> 

Je ne peux pas sembler juste définir le # foo-img w/h attributs Chaque fois que je charge une nouvelle image, elle est 50% plus petite! Voici quelque chose qui fonctionne, mais il semble énormément de code pour moi ..

 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> 

Répondre

1

Utilisez

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

pour vos images; spécifiant la largeur désirée (en pixels) de leurs conteneurs divs.

Questions connexes