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


当前回答

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 ...

其他回答

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

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

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

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

我对jQuery的看法

免责声明:这并不一定能回答这个问题,但可以拓宽我们的能力。它在jQuery 3.3.1中进行了测试

让我们考虑一下:

你有图像的URL/路径,你想要得到图像的宽度和高度,而不是在DOM上渲染它, 在DOM上呈现图像之前,您需要将offsetParent节点或图像div包装器元素设置为图像的宽度和高度,以便为不同的图像大小创建一个流体包装器,即,当单击按钮以查看模式/灯箱上的图像时

我要这样做:

// image path
const imageUrl = '/path/to/your/image.jpg'

// Create dummy image to get real width and height
$('<img alt="" src="">').attr("src", imageUrl).on('load', function(){
    const realWidth = this.width;
    const realHeight = this.height;
    alert(`Original width: ${realWidth}, Original height: ${realHeight}`);
})

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

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

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

当页面在JavaScript或jQuery中加载时,你可以像这样应用onload处理程序属性:

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

假设,我们想要得到<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将为我们提供元素在文档上呈现的尺寸。