It is actually very simple to use jquery to get the height of images in web pages. There are two common methods that can achieve our purpose
$("img").whith(); (returns a pure number)
$("img").css("width"); (returns a string : Number "px")
But sometimes you will encounter the situation of returning 0. The return value of the above method is actually 0 or 0px, which is very surprising
method 1 A long time ago, I used the solution, which is also the solution my master told me: add the width attribute to the
tag of the image you need to get , or write the description of the image in css, that’s it, so every time I want to get the height of an image, I need to measure the height of the image first, and then write it to the web page, so that’s it, Isn’t it very clumsy? Let’s look at the second method.
Method 2 Recently I was reading the original English version of Learning jQuery. Because I was translating and reading at the same time, I read every page very carefully, so I finally read it carefully. Read and experience the following two commonly used jquery event loading methods
$(function(){});
window.onload=function(){}
The first one is called after the DOM structure rendering is completed. At this time, in the web page Some resources have not been loaded, such as pictures and other resources, but the DOM structure has been rendered successfully
The second one is called after the DOM structure of the web page is rendered and the resources have been loaded successfully.
Do you feel the difference? One is called when the resource is not loaded, and the other is called after the resource loading is completed and the page has been rendered, so when we are in $(function(){} ) When calling $('img').width(), since the image has not been loaded, the height of the
tag is 0 at this time, so the return value is 0. But when you call it with window.onload=function(){}, the image has already been loaded, so you can get the height of the image at this time.
So remember, $(function(){}) is executed when the DOM rendering is completed and the resources have not been loaded. If you want to get some resource information, there is no way at this time.