JavaScript - 获取真实图像宽度和高度的功能(跨浏览器)

Sto*_*art -3 javascript height image width

如何通过JavaScript函数获得真实的图像宽度和高度(跨浏览器)?

Aro*_*eel 10

首先,如果您只是以更礼貌的方式提问,并提供尽可能多的相关信息,那么您有更大的机会回答您的问题.

无论如何...

据我所知,您可以在几乎所有浏览器中使用该.width属性:

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
Run Code Online (Sandbox Code Playgroud)


Azr*_*mil 8

var realWidth = $("#image").attr("naturalWidth");
var realHeight = $("#image").attr("naturalHeight");
Run Code Online (Sandbox Code Playgroud)