这里有新鲜出炉的 Javascript 教程,程序狗速度看过来!
Javascript 是一种由 Netscape 的 LiveScript 发展而来的原型化继承的基于对象的动态类型的区分大小写的客户端脚本语言,主要目的是为了解决服务器端语言,比如 Perl,遗留的速度问题,为客户提供更流畅的浏览效果。
有时需要获取图片的尺寸,这需要在图片加载完成以后才可以。有三种方式实现,下面一一介绍。 一、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 则表明图片已经加载完毕,停止轮询。该属性所有浏览器都支持。
来源: http://www.phperz.com/article/17/0422/276139.html