JavaScript - função para obter largura de imagem real & altura (cross browser)
-
22-07-2019 - |
Pergunta
Como obter largura de imagem real & altura (cross browser) por função JavaScript?
Solução
Em primeiro lugar, você tem uma maior chance de obter sua pergunta respondida se você tivesse acabado de perguntar isso de uma forma mais polida, e fornecendo o máximo de informações relevantes possível.
De qualquer forma ...
Para tanto quanto eu sei, você pode usar o propriedade .width
através de praticamente todos os 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
Outras dicas
var realWidth = $("#image").attr("naturalWidth");
var realHeight = $("#image").attr("naturalHeight");
Yay, Google !
Há algumas maneiras de fazer isso, dependendo exatamente o que você precisa (que você inutilmente omitido para incluir). Provavelmente o mais simples em um sentido geral é obter uma referência para o objeto de imagem e inspecionar as propriedades width
e height
.
jquery + <img src="" ... id="hello" />
+ $("#hello").width()