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


当前回答

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

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

其他回答

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

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

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

最近我有同样的问题,在一个错误的伸缩滑块。由于加载延迟,第一张图像的高度被设置得较小。我尝试了以下方法来解决这个问题,它是有效的。

// Create an image with a reference id. Id shall
// be used for removing it from the DOM later.
var tempImg = $('<img id="testImage" />');
// If you want to get the height with respect to any specific width you set.
// I used window width here.
tempImg.css('width', window.innerWidth);
tempImg[0].onload = function () {
    $(this).css('height', 'auto').css('display', 'none');
    var imgHeight = $(this).height();
    // Remove it if you don't want this image anymore.
    $('#testImage').remove();
}

// Append to body

$('body').append(tempImg);
// Set an image URL. I am using an image which I got from Google.
tempImg[0].src ='http://aspo.org/wp-content/uploads/strips.jpg';

这将为您提供相对于您设置的宽度的高度,而不是原始宽度或零。

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

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

尼基·德·梅耶要了一张背景照片;我只是从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()));
}