JavaScript: función para obtener el ancho de imagen real & amp; altura (navegador cruzado)

StackOverflow https://stackoverflow.com/questions/439358

Pregunta

Cómo obtener el ancho de imagen real & amp; altura (navegador cruzado) por la función de JavaScript?

¿Fue útil?

Solución

En primer lugar, tiene una mayor probabilidad de obtener una respuesta a su pregunta si la formula de una manera más educada y brindando la mayor cantidad de información relevante posible.

De todos modos ...

Hasta donde yo sé, puede usar la propiedad .width en casi todos los navegadores:

function getDimensions(id) {
    var element = document.getElementById(id);
    if (element && element.tagName.toLowerCase() == 'img') {
        return {
            width: element.width,
            height: element.height
        };
    }
}

<img id="myimage" src="foo.jpg" alt="" />

// using the function on the above image:
var dims = getDimensions('myimage');
alert(dims.width); --> shows width
alert(dims.height); --> shows height

Otros consejos

var realWidth = $("#image").attr("naturalWidth");
var realHeight = $("#image").attr("naturalHeight");

Sí, Google !

Hay algunas maneras de hacer esto dependiendo de exactamente lo que necesita (que ha omitido de manera inútil incluir). Probablemente lo más simple en un sentido general es obtener una referencia al objeto Imagen e inspeccionar las propiedades width y height .

jquery + < img src = " " ... id = " hola " / > + $("#hello").width()

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top