簡體   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