Home > Web Front-end > JS Tutorial > How to get image height and width using JS_javascript skills

How to get image height and width using JS_javascript skills

WBOY
Release: 2016-05-16 16:03:13
Original
1203 people have browsed it

Generally, the way to get the height and width of an image is:

Copy code The code is as follows:

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

But it cannot be obtained when tested in chrome. img.width, img.height are both 0

Cause: When the picture is not a local picture, but a network picture
onload event handler called when the image is loaded successfully.

While doing web development, there is a requirement: use Javascript to obtain the size of the image to be loaded, so naturally, I thought of the onload method of img. After completing the development under firefox, I went to IE to debug and found that img's The onload event is not called in many cases.

The original code is as follows:

Copy code The code is as follows:

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

This code looks fine, but why is onload not called by IE? Because IE caches images, the image loaded for the second time is not uploaded from the server, but loaded from the buffer. Doesn’t the onload event trigger for images loaded from the buffer? So I tested the following code and it worked~

Copy code The code is as follows:

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

Write onload to the front, first tell the browser how to process this image, and then specify the source of this image, this will be normal. Therefore, it is not that IE does not trigger the onload event, but because the buffer is loaded so fast that the onload event has already been triggered before img.onload is run. This reminds me of Ajax. When writing xmlhttp, we always specify the callback function of onstatechange first, and then send the data. The principle is the same

The above is the entire content of this article, I hope you all like it.

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template