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


当前回答

用jQuery库-

使用.width()和.height()。

更多jQuery宽度和jQuery高度。

示例代码:

$(文档)时函数(){ $("按钮”).click(函数() { alert(”图像的宽度 : " + $("# img_exmpl”).width ()); alert("形象的高度 : " + $("# img_exmpl”).height ()); }); }); < script src = " https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js " > < /脚本> <img id="img_exmpl" src="http://images.all-free-download.com/images/graphicthumb/beauty_of_nature_9_210287.jpg"> <button> img显示尺寸</button>

其他回答

这是我的方法:

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.

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

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

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

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

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

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

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

imageElement.naturalHeight

and

imageElement.naturalWidth

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