JavaScriptのイメージのonload関数からの画像の幅の値の取得

ハイテクオタク:

私は与えられた画像の幅を取得し、次があります。

<!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イベントハンドラが、私はからその幅にアクセスする本当の難し抱えてハンドラを。

私は馬鹿であることと、本当に簡単な何かが足りないか、それは私が考えるよりも、より複雑であるのですか?

すべてのヘルプは、最も高く評価されるだろう。

よろしく、スティーブ。

ルークNojek:

あなたが直面している問題は、非同期プログラミングです。onloadこの関数は後でエンジンによって呼び出され、プログラムは、その実行を開催します。

2つのオプションがあります。

  1. あなたはできるだけ早く値が必要な場合は、コード内で実行する必要があります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"
    
  2. 意志のアクセスがあること、コードの場合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);
    }
    

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=32411&siteId=1