如何使用JavaScript判斷圖片是否載入完成

來源:互聯網
上載者:User

有時需要擷取圖片的尺寸,這需要在圖片載入完成以後才可以。有三種方式實現,下面一一介紹。

一、load事件

<!DOCTYPE HTML>    <html>    <head>        <meta charset="utf-8">        <title>img - load event</title>    </head>    <body>        <img id="img1" src="http://pic1.win4000.com/wallpaper/f/51c3bb99a21ea.jpg">        <p id="p1">loading...</p>        <script type="text/javascript">            img1.onload = function() {                p1.innerHTML = 'loaded'            }        </script>    </body>    </html>

測試,所有瀏覽器都顯示出了“loaded”,說明所有瀏覽器都支援img的load事件。

二、readystatechange事件

<!DOCTYPE HTML>    <html>    <head>        <meta charset="utf-8">        <title>img - readystatechange event</title>    </head>    <body>        <img id="img1" src="http://pic1.win4000.com/wallpaper/f/51c3bb99a21ea.jpg">        <p id="p1">loading...</p>        <script type="text/javascript">            img1.onreadystatechange = function() {                if(img1.readyState=="complete"||img1.readyState=="loaded"){                    p1.innerHTML = 'readystatechange:loaded'                }            }        </script>    </body>    </html>

查看本欄目更多精彩內容:http://www.bianceng.cnhttp://www.bianceng.cn/webkf/script/

readyState為complete和loaded則表明圖片已經載入完畢。測試IE6-IE10支援該事件,其它瀏覽器不支援。

三、img的complete屬性

<!DOCTYPE HTML>    <html>    <head>        <meta charset="utf-8">        <title>img - complete attribute</title>    </head>    <body>        <img id="img1" src="http://pic1.win4000.com/wallpaper/f/51c3bb99a21ea.jpg">        <p id="p1">loading...</p>        <script type="text/javascript">            function imgLoad(img, callback) {                var timer = setInterval(function() {                    if (img.complete) {                        callback(img)                        clearInterval(timer)                    }                }, 50)            }            imgLoad(img1, function() {                p1.innerHTML('載入完畢')            })        </script>    </body>    </html>

輪詢不斷監測img的complete屬性,如果為true則表明圖片已經載入完畢,停止輪詢。該屬性所有瀏覽器都支援。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.