Javascript 如何在DOM中不附加此图像的情况下获得img高度?
我在data attr my元素中有原始图像src。我想得到这张照片的高度。但我不想将图像附加到DOM中。我怎样才能长得高?我的代码:Javascript 如何在DOM中不附加此图像的情况下获得img高度?,javascript,jquery,image,Javascript,Jquery,Image,我在data attr my元素中有原始图像src。我想得到这张照片的高度。但我不想将图像附加到DOM中。我怎样才能长得高?我的代码: const imgSrc = $target .closest('.js-photo-item') .find('.photos__img--value') .data('original-image'); const $img = $(new Image()).attr('src', imgSrc); console.log($img.heigh
const imgSrc = $target
.closest('.js-photo-item')
.find('.photos__img--value')
.data('original-image');
const $img = $(new Image()).attr('src', imgSrc);
console.log($img.height()) // this return 0
您需要先等待图像加载,而不是立即尝试检查高度。例如,请参见,您需要先等待图像加载,而不是立即尝试检查高度。比如说, 感谢您
George p
user。他的答案在上面
感谢您
George p
user。他在上面的回答…他没有使用load
,因为DOM中缺少元素您仍然可以为未添加到DOM的图像获取加载事件。他没有使用load
,因为DOM中缺少元素您仍然可以为未添加到DOM的图像获取加载事件。
const imgSrc = $target
.closest('.js-photo-item')
.find('.photos__img--value')
.data('original-image');
const $img = $(new Image()).attr('src', imgSrc);
$img.on('load', () => {
console.log($img[0].height) // return height img
});