JavaScript - function to get real image width & height (cross browser)

旧街凉风 提交于 2019-12-02 13:39:22

First of all, you have a greater chance of getting your question answered if you'd just ask it in a more polite way, and supplying as much relevant information as possible.

Anyway...

For as far as I know, you can use the .width property across pretty much all browsers:

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
var realWidth = $("#image").attr("naturalWidth");
var realHeight = $("#image").attr("naturalHeight");

Yay, Google!

There's a few ways to do this depending on exactly what you need (which you have unhelpfully omitted to include). Probably the simplest in a general sense is to get a reference to the Image object and inspect the width and height properties.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!