Home >Web Front-end >JS Tutorial >How to get image height and width using JS_javascript skills
Generally, the way to get the height and width of an image is:
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:
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~
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.