How to get image size (height & width) using JavaS

2018-12-31 00:59发布

Are there any jQuery or pure JS APIs or methods to get the dimensions of an image on the page?

23条回答
听够珍惜
2楼-- · 2018-12-31 01:21

it is important to remove the browser interpreted setting from the parent div. So if you want the real image width and height you can just use

$('.right-sidebar').find('img').each(function(){
    $(this).removeAttr("width");
    $(this).removeAttr("height");
    $(this).imageResize();
});

This is one TYPO3 Project example from me where I need the real properties of the image to scale it with the right relation.

查看更多
美炸的是我
3楼-- · 2018-12-31 01:24

You can only really do this using a callback of the load event as the size of the image is not known until it has actually finished loading. Something like the code below...

var imgTesting = new Image();

function CreateDelegate(contextObject, delegateMethod)
{
    return function()
    {
        return delegateMethod.apply(contextObject, arguments);
    }
}

function imgTesting_onload()
{
    alert(this.width + " by " + this.height);
}


imgTesting.onload = CreateDelegate(imgTesting, imgTesting_onload);
imgTesting.src = 'yourimage.jpg';
查看更多
与风俱净
4楼-- · 2018-12-31 01:26

clientWidth and clientHeight are DOM properties that show the current in-browser size of the inner dimensions of a DOM element (excluding margin and border). So in the case of an IMG element, this will get the actual dimensions of the visible image.

var img = document.getElementById('imageid'); 
//or however you get a handle to the IMG
var width = img.clientWidth;
var height = img.clientHeight;
查看更多
路过你的时光
5楼-- · 2018-12-31 01:26
var img = document.getElementById("img_id");
alert( img.height + " ;; " + img .width + " ;; " + img .naturalHeight + " ;; " + img .clientHeight + " ;; " + img.offsetHeight + " ;; " + img.scrollHeight + " ;; " + img.clientWidth + " ;; " + img.offsetWidth + " ;; " + img.scrollWidth )
//But all invalid in Baidu browser  360 browser ...
查看更多
情到深处是孤独
6楼-- · 2018-12-31 01:26

Before acquire element's attributes,the document page should be onload:

window.onload=function(){
    console.log(img.offsetWidth,img.offsetHeight);
}
查看更多
旧时光的记忆
7楼-- · 2018-12-31 01:29

ok guys, i think i improved the source code to be able to let the image load before trying to find out its properties, otherwise it will display '0 * 0', because the next statement would have been called before the file was loaded into the browser. Requires jquery...

function getImgSize(imgSrc){
    var newImg = new Image();
    newImg.src = imgSrc;
    var height = newImg.height;
    var width = newImg.width;
    p = $(newImg).ready(function(){
        return {width: newImg.width, height: newImg.height};
    });
    alert (p[0]['width']+" "+p[0]['height']);
}
查看更多
登录 后发表回答