是否有JavaScript或jQuery API或方法来获取页面上图像的尺寸?


当前回答

这是我的方法:

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.

其他回答

从父div中删除浏览器解释设置是很重要的。所以如果你想要真实的图像宽度和高度,你可以使用

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

这是我的一个TYPO3项目示例,我需要图像的真实属性来缩放它与正确的关系。

在使用真实图像大小之前,您应该加载源图像。如果使用jQuery框架,可以以简单的方式获得真实图像大小。

$("ImageID").load(function(){
  console.log($(this).width() + "x" + $(this).height())
})

这个答案正是我所寻找的(在jQuery):

var imageNaturalWidth = $('image-selector').prop('naturalWidth');
var imageNaturalHeight = $('image-selector').prop('naturalHeight');

在获取元素的属性之前,文档页面应该是onload的:

window.onload = function(){
    console.log(img.offsetWidth,img.offsetHeight);
}

我认为这可能对2019年使用JavaScript和/或TypeScript的人有所帮助。

我发现以下内容是不正确的,就像一些人认为的那样:

let img = new Image();
img.onload = function() {
  console.log(this.width, this.height) // Error: undefined is not an object
};
img.src = "http://example.com/myimage.jpg";

这是正确的:

let img = new Image();
img.onload = function() {
  console.log(img.width, img.height)
};
img.src = "http://example.com/myimage.jpg";

结论:

在onload函数中使用img,而不是this。