gpt4 book ai didi

javascript - 更改 src 后获取图像的高度

转载 作者:行者123 更新时间:2023-11-30 09:18:02 25 4
gpt4 key购买 nike

我有一个 img 元素,它的 src 属性为空。此图像的 src 是动态更改的(取决于用户要访问的页面)。

然后我需要检索图像的高度(不使用 jQuery)。

这是我的代码:

var myImg = document.getElementById("myImg");

myImg.src = "http://lorempicsum.com/rio/350/200/1";

console.log(myImg.height); // 0 (Expected : 200)
<img src="" alt="" id="myImg">

最佳答案

您正试图在设置 src 之后获取 height 并且图像还没有时间下载。您需要等到图像加载完毕,然后使用更合适的 window.getComputedStyle() 获取 height ,它考虑了 CSS 规则。

var myImg = document.getElementById("myImg");

// Set up a load event callback, which won't run until the image
// has been fully downloaded to the client.
myImg.addEventListener("load", function(){
// Use getComputedStyle() to get the most accurate information
console.log(getComputedStyle(myImg).height); // "200px"
});

// Only after you've configured the load callback function should you change the source.
myImg.src = "http://lorempicsum.com/rio/350/200/1";
<img src="" alt="" id="myImg">

关于javascript - 更改 src 后获取图像的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53695963/

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