javascript判断图片加载完成的三种方法

有时需要获取图片的尺寸,这需要在图片加载完成以后才可以

1.load 事件

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

2.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>

3.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>
posted @ 2018-10-17 10:37  QiuYuLing  阅读(503)  评论(0编辑  收藏  举报