gpt4 book ai didi

javascript - 如何通过javascript获取图像的大小?

转载 作者:行者123 更新时间:2023-12-01 01:38:08 24 4
gpt4 key购买 nike

我试图通过javascript获取图像大小,因为我使用了offsetHeight、scrollHeight、clientHeight,但这些都不起作用。 naturalHeight 属性有效,但它返回图像的实际大小,即使图像通过 css 调整大小。奇怪的是,如果我单击“尝试”按钮,那么相同的代码就可以正常工作。我哪里错了?
请解释一下:

  1. 为什么当我通过单击按钮执行代码时,代码运行良好?
  2. 当图像通过css或屏幕尺寸调整大小时,如何获取图像大小?

var imageHeightMethodOne = document.querySelector('.one').offsetHeight;
console.log('MT1-The height of img is ' + imageHeightMethodOne);
var imageHeightMethodTwo = document.querySelector('.one').scrollHeight;
console.log('MT2-The height of img is ' + imageHeightMethodTwo);
var imageHeightMethodThree = document.querySelector('.one').clientHeight;
console.log('MT3-The height of img is ' + imageHeightMethodThree);
var imageHeightMethodFour = document.querySelector('.one').naturalHeight;
console.log('MT4-The height of img is ' + imageHeightMethodFour);

function test() {
var imageHeightMethodOne = document.querySelector('.one').offsetHeight;
console.log('MT1-The height of img is ' + imageHeightMethodOne);
var imageHeightMethodTwo = document.querySelector('.one').scrollHeight;
console.log('MT2-The height of img is ' + imageHeightMethodTwo);
var imageHeightMethodThree = document.querySelector('.one').clientHeight;
console.log('MT3-The height of img is ' + imageHeightMethodThree);
var imageHeightMethodFour = document.querySelector('.one').naturalHeight;
console.log('MT4-The height of img is ' + imageHeightMethodFour);
}
<div class='container' style='width:40%;'>
<img class='one' src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcT6K8uN-QjZpaY10m_SQvqnwXDr8vqQijLi_XhZrJqSLDkMz5vvag' style='width:100%;height:auto;' />
</div>
<button onclick='test()'>try</button>

最佳答案

function test() {
var imageHeightMethodOne = document.querySelector('.one').offsetHeight;
console.log('MT1-The height of img is ' + imageHeightMethodOne);
var imageHeightMethodTwo = document.querySelector('.one').scrollHeight;
console.log('MT2-The height of img is ' + imageHeightMethodTwo);
var imageHeightMethodThree = document.querySelector('.one').clientHeight;
console.log('MT3-The height of img is ' + imageHeightMethodThree);
var imageHeightMethodFour = document.querySelector('.one').naturalHeight;
console.log('MT4-The height of img is ' + imageHeightMethodFour);
}
<body onload="test();">
<div class='container' style='width:40%;'>
<img class='one' src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcT6K8uN-QjZpaY10m_SQvqnwXDr8vqQijLi_XhZrJqSLDkMz5vvag' style='width:100%;height:auto;' />
</div>
<button onclick='test()'>try</button>
</body>

在onLoad事件中调用该函数。这将确保页面的资源已加载,包括图像、CSS。

关于javascript - 如何通过javascript获取图像的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52646393/

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