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


当前回答

clientWidth和clienttheight是DOM属性,显示DOM元素内部维度的当前浏览器大小(不包括边距和边框)。在IMG元素的情况下,这将得到可见图像的实际尺寸。

var img = document.getElementById('imageid'); 
//or however you get a handle to the IMG
var width = img.clientWidth;
var height = img.clientHeight;

其他回答

你还可以使用:

var image=document.getElementById("imageID");
var width=image.offsetWidth;
var height=image.offsetHeight;

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

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

假设,我们想要得到<img id="an-img" src"…" >

// Query after all the elements on the page have loaded.
// Or, use `onload` on a particular element to check if it is loaded.
document.addEventListener('DOMContentLoaded', function () {
  var el = document.getElementById("an-img");

  console.log({
    "naturalWidth": el.naturalWidth, // Only on HTMLImageElement
    "naturalHeight": el.naturalHeight, // Only on HTMLImageElement
    "offsetWidth": el.offsetWidth,
    "offsetHeight": el.offsetHeight
  });
})

自然维度

埃尔。naturalWidth和el。naturalHeight会得到图像文件的自然尺寸。

布局尺寸

埃尔。offsetWidth和el。offsetHeight将为我们提供元素在文档上呈现的尺寸。

const file = event.target.files[0];
const img = new Image();
img.onload = function () {
  width = img.width;
  height = img.height;
};
img.src = URL.createObjectURL(file);
alert(width + "x" + height);

尼基·德·梅耶要了一张背景照片;我只是从CSS内容中获取它,并替换“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()));
}