我是一个图像元素。我让用户上传图片。 上传后,我处理图像。我想加载处理过的图像并显示它。 我得到了并且显示图像就好了。
我还需要知道所加载图像的宽度和高度。
我正如下面所做的那样正确,它应该有效,但不确定为什么我将宽度和高度设为零:
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???
}
});
答案 0 :(得分:2)
jQueryObject.width()
将返回目标元素的computedStyle
如果在CSS中强制使用此元素的width
和height
值,则会返回这些强制值。
如果要获取已加载图片的大小,您需要检查naturalWidth
元素的naturalHeight
和<img>
属性:
w = this.naturalWidth;
h = this.naturalHeight;
答案 1 :(得分:0)
我尝试了很多方法, 你的方式:
var img = $("#photo").attr('src', '/photo/get/' + id)
.on('load', function () {
Output: Nothing.
使用 .load():
var img = $("#photo").attr('src', '/photo/get/' + id)
.load( function () {
Output: Nothing.
使用 .ready():
var img = $("#photo").attr('src', '/photo/get/' + id)
.ready( function () {
Output: "Could not load image".
所以它不起作用。也许那里有一些马车。
但是当我使用时,
var img = $("#photo").attr('src', '/photo/get/' + id)
.on('click', function () {
Output: "Image loaded";"width=280 height=160".
在适当的高度和宽度下,它完美地工作。 在你的代码中没有错误的东西(“load”,)或load()。
P.S。 jQuery:ver:1.11.3。浏览器:IE:11.0,Firefox:40.0,Opera:32.0