首页 > 代码库 > js获取图片是否加载完毕

js获取图片是否加载完毕

Snandy

If you cannot hear the sound of the genuine in you, you will all of your life spend your days on the ends of strings that somebody else pulls.

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>

 

技术分享

 

js获取图片是否加载完毕