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:30
var imgSrc, imgW, imgH;
function myFunction(image){
    var img = new Image();
    img.src = image;
    img.onload = function() {   
        return {
            src:image,
            width:this.width,
            height:this.height};
        }
    return img;
}
var x = myFunction('http://www.google.com/intl/en_ALL/images/logo.gif');
    //Waiting for the image loaded. Otherwise, system returned 0 as both width and height.
x.addEventListener('load',function(){
    imgSrc = x.src;
    imgW = x.width;
    imgH = x.height;
});
x.addEventListener('load',function(){
    console.log(imgW+'x'+imgH);//276x110
});
console.log(imgW);//undefined.
console.log(imgH);//undefined.
console.log(imgSrc);//undefined.

This is my method, hope this helpful. :)

查看更多
情到深处是孤独
3楼-- · 2018-12-31 01:34

Using JQuery you do this:

var imgWidth = $("#imgIDWhatever").width();
查看更多
零度萤火
4楼-- · 2018-12-31 01:35

The thing all other have forgot is that you cant check image size before it loads. When the author checks all of posted methods it will work probably only on localhost. Since jQuery could be used here, remember that 'ready' event is fired before images are loaded. $('#xxx').width() and .height() should be fired in onload event or later.

查看更多
人气声优
5楼-- · 2018-12-31 01:35

Nicky De Maeyer asked after a background picture; I simply get it from the css and replace the "url()":

var div = $('#my-bg-div');
var url = div.css('background-image').replace(/^url\(\'?(.*)\'?\)$/, '$1');
var img = new Image();
img.src = url;
console.log('img:', img.width + 'x' + img.height); // zero, image not yet loaded
console.log('div:', div.width() + 'x' + div.height());
img.onload = function() {
  console.log('img:', img.width + 'x' + img.height, (img.width/div.width()));
}
查看更多
怪性笑人.
6楼-- · 2018-12-31 01:35

You can apply the onload handler property when the page loads in js or jquery like this:-

$(document).ready(function(){
   var width = img.clientWidth;
   var height = img.clientHeight;

 });
查看更多
登录 后发表回答