我需要获取从 API 加载的图像的宽度和高度,不会将 css 应用于图像。图像可能具有可变大小,具体取决于 API 中加载的内容/
目前使用 jquery 或 vanilla js 我总是得到 0 的宽度和高度?
我的代码有什么问题?创建 img 标签时是否应该动态设置宽度和高度?怎么做?
this.getItemSize = function() {
var elm = $('#' + scope.elmItem);
var pos = elm.offset();
/* also with this vanila js does not work
var image = document.getElementById(scope.elmItem);
console.log(image);
var width = image.offsetWidth;
var height = image.offsetHeight;
*/
scope.itemTop = pos.top;
scope.itemLeft = pos.left;
scope.itemWidth = elm.width();
scope.itemHeight = elm.height();
console.log(scope.itemTop + " " + scope.itemLeft + " " + scope.itemWidth + " " + scope.itemHeight);
};
$.get(this.url, function(image) {
// add img to the dom
var img = $('<img id="item">');
img.attr('src', scope.url);
img.appendTo('#' + scope.elm);
scope.getItemSize();
});