使用 jQuery 动态创建图像并检索尺寸
所以我动态创建一个图像,我希望获得图像尺寸。是否可以在将图像附加到 DOM 之前执行此操作?目前我正在这样做:
var arrow = $('<img src="' + parameters.arrowRight + '" />');
arrow.load(function() {
console.log("size: " + $(this).height() + " " + $(this).width());
});
但高度和宽度都报告为零。该图像实际上正在被获取,因为我可以在 firebug 中看到 GET 请求。
So I am dynamically creating an image and I wish to get the image dimensions. Is it possible to do this before the image is attached to the DOM? At the moment I am doing this:
var arrow = $('<img src="' + parameters.arrowRight + '" />');
arrow.load(function() {
console.log("size: " + $(this).height() + " " + $(this).width());
});
but the height and width are both reported as zero. The image is actually being fetched as I can see the GET request in firebug.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不可以。在将任何元素附加到 DOM 之前,无法获取该元素的尺寸。
解决方法是为图像指定 css:
margin-left: -10000px
。然后您可以附加它,但它将不可见。然后您可以获得其尺寸并根据需要进行处理。No. It is not possible to get the dimensions of any element until it is attached to the DOM.
A workaround would be to give the image the css:
margin-left: -10000px
. You can then append it, but it will not be visible. You can then get its' dimensions and do with it as required.也许这会有所帮助:
http://api.jquery.com/load-event/
maybe this will help:
http://api.jquery.com/load-event/