gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 10:09:35 25 4
gpt4 key购买 nike

所以我有这段 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);

最佳答案

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

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

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

关于javascript - Js - 如何每次都获取图像大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37719739/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com