Home > Web Front-end > JS Tutorial > Two ways to get the height of images in web pages using jquery_jquery

Two ways to get the height of images in web pages using jquery_jquery

WBOY
Release: 2016-05-16 17:21:12
Original
1217 people have browsed it

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

Copy code The code is as follows:

$("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
Copy code The code is as follows:

$(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.
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