亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

無法使用 JS 獲取 HTML 中圖像的實際大小

無法使用 JS 獲取 HTML 中圖像的實際大小

aluckdog 2022-08-27 14:09:29
我有一個從外部資源獲得的球的圖像,我需要獲取圖像的大?。ǜ叨群蛯挾龋┮赃M行進一步的計算,但我嘗試的內容顯示0(但實際上它是40px)下面是整個代碼:<!DOCTYPE html><html dir="ltr">  <head>    <meta charset="utf-8">    <title>Ball to center</title>    <style>      #field {        width: 200px;        border: 10px groove black;        background-color: #00FF00;        position: relative;      }      #ball {        position: absolute;      }    </style>  </head>  <body>    <div id="field">      <img src="https://en.js.cx/clipart/ball.svg" id="ball"> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .      . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .    </div>    <script type="text/javascript">      let field = document.getElementById('field');      let ball = document.getElementById('ball');      console.log(`natural height and width: ${ball.naturalHeight} - ${ball.naturalWidth}`);      console.log(`client height and width: ${ball.clientHeight} - ${ball.clientWidth}`);    </script>  </body></html>
查看完整描述

2 回答

?
慕碼人2483693

TA貢獻1860條經驗 獲得超9個贊

您的方法的問題在于代碼是在加載頁面之前執行的。如這里所示,您可以使用vanilla javascript執行類似操作,直到頁面加載。


let field = document.getElementById('field');

let ball = document.getElementById('ball');


window.onload = () => {

  console.log(`natural height and width: ${ball.naturalHeight} - ${ball.naturalWidth}`);

  console.log(`client height and width: ${ball.clientHeight} - ${ball.clientWidth}`);  

};


查看完整回答
反對 回復 2022-08-27
?
素胚勾勒不出你

TA貢獻1827條經驗 獲得超9個贊

您只應在圖像加載后檢查圖像的大小??梢允褂?image 元素的屬性來查看它是否已加載,否則會將處理程序附加到 load 事件。loaded


let ball = document.getElementById('ball');


const checkImgSize = el => {

    console.log(`natural height and width: ${el.naturalHeight} - ${el.naturalWidth}`);

    console.log(`client height and width: ${el.clientHeight} - ${el.clientWidth}`);

};


if( ball.loaded )

    checkImgSize(ball);

else 

    ball.addEventListener('load', function(){ checkImgSize(this) }, { once: true });


查看完整回答
反對 回復 2022-08-27
  • 2 回答
  • 0 關注
  • 89 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號