Js - 如何每次都获得图像大小

时间:2016-06-09 07:41:44

标签: javascript jquery css

所以我有一些Jquery代码,代码的目的是显示一个适合我的屏幕尺寸的图像。图像是动态加载的,即:它们将在需要时生成。我遇到的问题是,当我第一次加载图片时,图片的heightwidth0。我有办法确保始终获得图像的大小吗?

到目前为止我的代码看起来像这样:

    var parent = document.getElementById('gallery-lightBox-large'),
        image = originalImages[currentIndex],
        original = document.createElement('img');

    parent.innerHTML = '';

    original.src = image.Url;

    var windowHeight = window.innerHeight * 0.8,    //  Allow for 10% margin
        windowWidth = window.innerWidth * 0.8;      //  Allow for 10% margin

    original.style.opacity = '0';
    original.style.position = 'absolute';
    original.style.zIndex = '-99';
    parent.appendChild(original);
    //console.info('original : ' + original.clientHeight, original.clientWidth);

    var elem = document.createElement('img');
    elem.src = image.Url;
    elem.clientHeight = original.clientHeight;
    elem.clientWidth = original.clientWidth;

    var width,
        height;

    if (windowHeight < windowWidth) {   //  Landscape mode
        if (original.clientWidth > windowWidth) {
            width = windowWidth;
        } else {
            width = original.clientWidth;
        }

        if (original.clientHeight > windowHeight) {
            width = undefined;
            height = windowHeight;
        } else {
            height = original.clientHeight;
        }
    } else {    //  Portrait mode
        if (original.clientHeight > windowHeight) {
            height = windowHeight;
        } else {
            height = original.clientHeight;
        }

        if (original.clientWidth > windowWidth) {
            height = undefined;
            width = windowWidth;
        } else {
            width = original.clientWidth;
        }
    }

    if (width != undefined) {
        if (width === 0) {
            width = 200;
        }
        elem.width = width;
    }

    if (height != undefined) {
        if (height === 0) {
            height = 200;
        }
        elem.height = height;
    }

    parent.appendChild(elem);

2 个答案:

答案 0 :(得分:1)

您可以尝试这种方式在加载后检查图像大小

var img= document.getElementById('imgid');

img.onload = function () {
    alert(img.width + "," + img.height);       
};

答案 1 :(得分:0)

根据Martin Gottweis的建议(我非常欢迎谁接受我的接受;-))

我的解决方案如下:

var parent = document.getElementById('gallery-lightBox-large'),
    image = originalImages[currentIndex];
var elem = document.createElement('img');
elem.src = image.Url;
parent.appendChild(elem);

用这个css

#gallery-lightBox-large img {
    max-height:70vh;
    max-width: 70vw;
}