Sometimes you need to get the size of the picture, which needs to be done after the picture is loaded. There are three ways to achieve this, as described below.
First, the Load event
<! DOCTYPE html> <meta charset="Utf-8"> <title>Img-load Event</title> <body> 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>
Test, all browsers show "loaded", indicating that all browsers support IMG's Load event.
Ii. ReadyStateChange Events
<! DOCTYPE html> <meta charset="Utf-8"> <title>Img-readystatechange Event</title> <body> 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>
ReadyState for complete and loaded indicates that the picture has been loaded. The test Ie6-ie10 supports this event and is not supported by other browsers.
Third, the Complete property of img
<! DOCTYPE html> <meta charset="Utf-8"> <title>img-complete attribute</title> <body> 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 ('Load Complete')}) </script> </body>
Three ways to use JavaScript to determine whether a picture is loaded