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


当前回答

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

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

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

其他回答

其他所有人都忘记了的事情是,你不能在加载前检查图像大小。当作者检查所有发布的方法时,它可能只在本地主机上工作。

由于这里可以使用jQuery,请记住'ready'事件是在图像加载之前触发的。$('#xxx').width()和.height()应该在onload事件或以后触发。

我认为这可能对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。

此外(除了Rex和Ian的回答)还有:

imageElement.naturalHeight

and

imageElement.naturalWidth

它们提供了图像文件本身的高度和宽度(而不仅仅是图像元素)。

如果你正在使用jQuery并且你正在请求图像大小,你必须等待它们加载,否则你只会得到零。

$(document).ready(function() {
    $("img").load(function() {
        alert($(this).height());
        alert($(this).width());
    });
});

要得到自然的高度和宽度:

.naturalHeight document.querySelector (img); .naturalWidth document.querySelector (img); < img src = " img.png " >

如果你想获取样式的高度和宽度:

document.querySelector(“img”).offsetHeight; document.querySelector(“img”).offsetWidth;