remove outerwidth attribute javascript jquery

javascript - attribute - outerwidth



jQuery width() y height() devuelven 0 para el elemento img (7)

Así que estoy creando un nuevo elemento de imagen una vez que recibo respuesta de una llamada AJAX con metadatos de imagen como este:

var loadedImageContainter = $(''<div class="loaded-image-container"></div>''); var image = $(''<img src="'' + file.url + ''" alt="">''); loadedImageContainter.append(image); $(''.loading-image'').replaceWith(loadedImageContainter); var width = image.width(); var height = image.height(); console.log(width); console.log(height);

Pero las funciones width () y height () están devolviendo 0, aunque la imagen tiene un tamaño de 30 x 30 px y aparece correctamente en la página. Necesito obtener sus dimensiones para posicionar absolutamente la imagen.


Como @ahren said anteriormente, la razón es que la imagen no se carga cuando intentas obtener sus tamaños.

Si desea solucionar este problema sin jQuery, puede usar el método addEventListener JS addEventListener :

document.getElementsByTagName(''img'')[0].addEventListener(''load'', function() { // ... var width = image.width(); var height = image.height(); console.log(width); console.log(height); // ... });


Debe esperar hasta que la imagen se haya cargado para tener acceso a los datos de ancho y alto.

var $img = $(''<img>''); $img.on(''load'', function(){ console.log($(this).width()); }); $img.attr(''src'', file.url);

O con llanura JS:

var img = document.createElement(''img''); img.onload = function(){ console.log(this.width); } img.src = file.url;

Además, no necesita insertar la imagen en el DOM antes de leer los valores de ancho y alto, por lo que podría dejar su .loading-image hasta después de calcular todas las posiciones correctas.


Eso es porque tu imagen no se carga cuando verificas el ancho

Trate de usar el evento de carga de esta manera

$(''img'').on(''load'',function(){ // check width });


Para mi solo funciona con "appendTo"

$(''<img src="myImage.jpeg">'').load(function(){ $w = $(this).width(); $h = $(this).height(); $(this).remove() }).appendTo("body")


Prueba esto:

$(''.loading-image'').replaceWith(loadedImageContainter); $(''.loading-image'').load(function(){ var width = image.width(); var height = image.height(); console.log(width); console.log(height); });


Si lo pones dentro de la llamada AJAX, eso también funcionará, esto es para el método json

$.post("URL",{someVar:someVar},function(data){ var totalImgs = $(''body'').find(''img'').length; var image = $(''<img src="'' + data.file[0].url + ''" alt="" id="IMG_''+ totalImgs +''">''); loadedImageContainter.append(image); $(''.loading-image'').replaceWith(loadedImageContainter); var width = $(''#IMG_''+totalImgs).width(); var height = $(''#IMG_''+totalImgs).height(); },''json'');


También puede usar el método alternativo API $.load :

$(''<img src="'' + file.url + ''" alt="">'').load( function(){ <your function implementation> });