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

时间:2018-10-04 12:11:19

标签: 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>

2 个答案:

答案 0 :(得分:2)

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 :(得分:0)

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

2:重复的问题。

Google查询: dom图片高度

最佳结果How to get image size (height & width) using JavaScript?