2012-06-21 21 views
13

¿Por qué clientWidth/Height devuelve 0 en IE, Chrome y Safari? pero en Firefox y Opera funciona bien. He utilizado este código:clientWidth y clientHeight returns 0

$(document).ready(function() { 

    var imgs = document.getElementsByTagName('img'); 
    var imgLength = imgs.length; 

    for (var i = 0; i <= imgLength - 1; i++) { 

     var imgWidth = imgs[i].clientWidth; 
     var imgHeight = imgs[i].clientHeight; 

     $('img').eq(i).attr({ 
      width: imgWidth, 
      height: imgHeight 
     }); 

     console.log(imgWidth); 
    } 

    console.log(imgLength); 

}); 

alguna idea? Gracias.

he intentado con window.load con ClientWidth sus obras excelentes para Firefox, Chrome y Opera pero otros no

+0

Si está utilizando jquery pls use la propiedad innerWidth() en lugar del ancho del cliente –

+0

@Ajaybeniwal ~ en este ejemplo particular, no, no es mejor usar jQuery. En general, es más rápido hacer referencia a las propiedades nativas que llamar a las funciones de jQuery, y el OP tiene un manejador en un objeto JS DOM nativo de todos modos; ¿Por qué tomarse la molestia de envolver eso en un objeto jQuery e incurrir en gastos generales adicionales? –

+0

Recientemente he respondido sobre una pregunta similar; es posible que desee [leer eso también] (http://stackoverflow.com/a/11116604/304588). Parece que es el mismo problema. –

Respuesta

-5

Creo que sería mejor si se utiliza jQuery para obtener la altura y anchura, ya que funciona bien en todos los navegadores, por lo que su código sería algo como esto: -

$(document).ready(function() { 


    var imgs = $('img'); 
    var imgLength = imgs.length; 

    for(var i=0; i<= imgLength-1;i++){ 

     var imgWidth = imgs[i].width(); 
     var imgHeight = imgs[i].height(); 

     $('img').eq(i).attr({width:imgWidth, height: imgHeight}); 

     console.log(imgWidth); 
    } 

    console.log(imgLength); 

}); 
-3

Si desea obtener dimensiones, incluyendo márgenes y los bordes tratar de usar las funciones de jQuery outerWidth y outerHeight. Deben tener cuidado con las diferencias entre navegadores. http://api.jquery.com/outerwidth/

Si desea obtener solo las dimensiones de los contenidos de un elemento (sin márgenes, bordes, almohadillas) utilice width y height. http://api.jquery.com/width/

Cuestiones relacionadas