Home > Web Front-end > JS Tutorial > The correct way to get the size of dynamically loaded images in JQ_jquery

The correct way to get the size of dynamically loaded images in JQ_jquery

WBOY
Release: 2016-05-16 17:16:41
Original
1748 people have browsed it

There are some error-prone methods of obtaining the size of dynamically loaded images. The main reasons for errors are:
You call the code before the image is downloaded from the web page. In this case, It is not easy to find when developing on the machine.
The BUG of jQuery load() event processing. When the image is obtained from the browser cache, the wrong size is obtained.
The wrong code is:
(Error ) Call the code to get the dimensions immediately after adding the HTML

Copy code The code is as follows:

 var html = '';
 $(' #my_div').html(html);
 var width = $('#my_div img').width(); // may return 0

(Error) Use jQuery’s load() event handling

Copy code The code is as follows:

var html = '';
var img = $(html);
 html.load(function(){
 // return 0 if image is loaded from browser cache
 var width = img.width();
 });
 $('#my_div').html(img);

The following is the truly correct method, using the JavaScript Image class:
Correct method

Copy code The code is as follows:

var html = '';
$('#my_div').html(html);
var ni = new Image();
ni .onload = function(){
 var width = ni.width;
 }
 ni.src = img.attr(URL);
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