我是一个图像元素。我让用户上传图像。 上传后,我处理图像。我想加载处理后的图像并显示它。 我得到并显示图像很好。
我还需要知道加载图像的宽度和高度。
我按照下面的方式正确执行此操作,它应该可以工作,但不确定为什么我的宽度和高度为零:
HTML:
<img id="photo" src="">
JS:
var id = 1000;
var img = $("#photo").attr('src', '/photo/get/' + id)
.on('load', function () {
var w = 0;
var h = 0;
if (!this.complete || typeof this.naturalWidth === "undefined" || this.naturalWidth === 0) {
alert("Could not load image");
}
else {
alert('Image loaded');
w = $(this).width();
h = $(this).height();
alert("width=" + w + " height=" + h);//PRINTS 0, 0, WHY???
}
});
最佳答案
jQueryObject.width()
将返回目标元素的计算样式。
如果在 CSS 中强制 width
和height
该元素的值,那么它将返回那些强制值。
如果您想获取加载图像的大小,您需要的是检查 naturalWidth
和naturalHeight
您的<img>
的属性元素:
w = this.naturalWidth;
h = this.naturalHeight;
关于javascript - 为什么加载后无法获取图像宽度和高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32918223/