繁体   English   中英

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

[英]How can I get the size of images by javascript?

我试图通过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。

1:到那时,页面已加载,浏览器绘制了布局,因此存在尺寸。

2:重复的问题。

Google查询: dom图片高度

最佳结果: 如何使用JavaScript获取图像大小(高度和宽度)?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM