jquery - 使用 jquery 查找动态加载但 DOM 附加图像的尺寸?

标签 jquery css ajax image dimensions

我正在使用 ajax 动态加载图像源,其中 s 是此源。我在 DOM 中创建一个图像元素,加载后将此源分配给它,然后将其附加到名为 imgwrapperdiv。然后我尝试获取图像的尺寸,但它不起作用。我知道您无法获取动态加载的图像的尺寸,但即使在附加到 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/

相关文章:

JavaScript 的 onmouseout 事件没有按预期工作

html - 子元素清除父元素的CSS

jquery - 使用 jQuery 更改 css 属性值

javascript - 使用 select2 4.0.3 创建下拉列表数组并禁用基于其他 select2 值的选项

php - style.css 不影响新页面模板

javascript - jQuery AJAX 在窗口卸载时触发错误回调 - 如何过滤掉卸载并只捕获真正的错误?

javascript - Ember 显示来自 ajax 调用的数据

jquery - History.back() 在 ajax 成功函数后不起作用

jQuery Mobile 输入字段错误样式

html - 父 <span> 样式不适用于子 <p>