Home  >  Article  >  Web Front-end  >  JS获取图片高度宽度的方法分享_javascript技巧

JS获取图片高度宽度的方法分享_javascript技巧

WBOY
WBOYOriginal
2016-05-16 16:03:131154browse

一般获取图片高度宽度的写法:

复制代码 代码如下:

var img = new Image();
img.src = imgsrc;
var imgWH = CalcImgTiple(img.width, img.height);

但chrome中测试 无法获取到。img.width, img.height都为0

原因:当图片不是本地图片,而是网络图片
onload 在成功地装载了图像时调用的事件处理程序。

在做web开发,其中有一个需求:利用Javascript获取要加载的图片的尺寸,所以很自然的,想到了img的onload方法,在firefox下开发完成后,到IE下调试,发现img的onload事件很多情况下都不被调用。

最初的代码如下:

复制代码 代码如下:

var img = new Image;
img.src = "test.gif";
img.onload = function(){
alert ( img.width );
};

这段代码看着没什么问题,但是为什么onload没有被IE调用呢?因为IE会缓存图片,第2次加载的图片,不是从服务器上传过来的,而是从缓冲区里加载的。是不是从缓冲区里加载的图片就不触发onload事件呢?我于是我测试了以下代码,成功了~

复制代码 代码如下:

var img = new Image;
img.onload = function(){
alert ( img.width );     };
img.src = "test.gif";

把onload写到前面去,先告诉浏览器如何处理这张图片,再指定这张图片的源,这样就正常了。所以,不是IE没有触发onload事件,而是因为加载缓冲区的速度太快,以至于没有运行到img.onload的时候,onload事件已经触发了。这让想到了Ajax,在写xmlhttp的时候,都是先指定onstatechange的回调函数,然后再send数据的,道理是一样的

以上所述就是本文的全部内容了,希望大家能够喜欢。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn