[英]Failed getting Image width from its onload function using Promise in TS
[英]Getting Value of Image Width from JavaScript Image Onload Function
我有以下獲取給定圖像的寬度:
<!DOCTYPE html>
<html>
<head>
<title>Image Width</title>
<script>
var img = new Image();
img.onload = function() {
alert("Width: " + img.width);
};
img.src="http://www.hq.nasa.gov/office/pao/History/alsj/misc/apmisc-60-SAT-1.jpg"
// Do something with 'img.width' here, outside the image onload event handler.
</script>
</head>
<body>
</body>
</html>
我明白,我需要的圖像負載獲得它的寬度,以及如何從圖像的onload事件處理程序中得到它的寬度之前,但我有從外面處理程序訪問其寬度實際困難。
我只是一個白痴,遺漏了一些非常簡單的東西,還是比我想象的更復雜?
非常感激任何的幫助。
問候,史蒂夫。
您面臨的問題是異步編程。 onload
函數稍后會被引擎調用,程序會暫停執行。
有兩種選擇:
如果您需要盡快獲得該值,則必須在onload
運行代碼,例如:
var img = new Image(); img.onload = function() { alert("Width: " + img.width); // Do something with 'img.width' here, outside the image onload event handler. }; img.src="http://www.hq.nasa.gov/office/pao/History/alsj/misc/apmisc-60-SAT-1.jpg"
如果稍后訪問img.width
的代碼將發生,例如在用戶單擊某些內容后,您可以存儲該值並在其他地方使用它:
var width; var img = new Image(); img.onload = function() { width = img.width; }; img.src="http://www.hq.nasa.gov/office/pao/History/alsj/misc/apmisc-60-SAT-1.jpg" function anotherFunction() { alert(width); }
我不確定我理解你想要做什么,但如果你想訪問圖像的寬度,那么我建議你閱讀更多關於異步代碼的信息。
img.onload = function() {}
代碼的作用是安排在圖像加載后調用的函數。
然而,它后面的代碼只是在調度發生后立即(同步)執行,這肯定會在加載圖像之前執行。
因此,您需要延遲它的執行,直到加載圖像,這正是img.onload
的意義所在。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.