如何检索延迟图像的宽度和高度?

时间:2013-07-08 08:11:35

标签: javascript jquery

我需要获取从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();
            });

1 个答案:

答案 0 :(得分:0)

您需要在加载图像后调用getItemSize,您可以使用.load()事件处理程序来执行此操作

$.get(this.url, function(image) {
    // add img to the dom
    var img = $('<img id="item">');
    img.load(function(){
        scope.getItemSize();
    })
    img.attr('src', scope.url);
    img.appendTo('#' + scope.elm);