我正在使用 ajax 动态加载图像源,其中 s
是此源。我在 DOM 中创建一个图像元素,加载后将此源分配给它,然后将其附加到名为 imgwrapper
的 div
。然后我尝试获取图像的尺寸,但它不起作用。我知道您无法获取动态加载的图像的尺寸,但即使在附加到 DOM 之后也无法获取?
我的代码如下:
//use ajax to get value of s (the image source)
img = document.createElement("img");
img.src = s;
$('#imgwrapper').appendChild(img);
console.log($('#imgwrapper').find('img').width());
这返回 0,而不是给我图像的宽度。
最佳答案
等待图片加载完毕
//use ajax to get value of s (the image source)
img = document.createElement("img");
img.onload = function() {
console.log($('#imgwrapper').find('img').width());
};
img.src = s;
$('#imgwrapper').append(img);
编辑
正如@MattiasBuelens 提到的。 jQuery 对象没有 .appendChild()
。那应该是 .append()
而不是
关于jquery - 使用 jquery 查找动态加载但 DOM 附加图像的尺寸?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14335503/