zoukankan      html  css  js  c++  java
  • JavaScript判断图片是否加载完成

    一、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>

    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则表明图片已经加载完毕,停止轮询。该属性所有浏览器都支持。

  • 相关阅读:
    [BZOJ] 1623: [Usaco2008 Open]Cow Cars 奶牛飞车
    [BZOJ] 3631: [JLOI2014]松鼠的新家
    [BZOJ] 1775: [Usaco2009 Dec]Vidgame 电视游戏问题
    [BZOJ] 1619: [Usaco2008 Nov]Guarding the Farm 保卫牧场
    [Codeforces] #432 div.2 (Virtual)
    [BZOJ] 1819: [JSOI]Word Query电子字典
    [Codeforces] #436 E. Fire
    [Codeforces] #436 D. Make a Permutation!
    [Codeforces] #436 C. Bus
    [Codeforces] #436 B. Polycarp and Letters
  • 原文地址:https://www.cnblogs.com/axl234/p/3765684.html
Copyright © 2011-2022 走看看