How to Use JQ to obtain the size of Dynamically Loaded Images

Source: Internet
Author: User

There are some methods that are prone to errors to obtain the size of Dynamically Loaded Images. The main cause of the error is:
You can call the code before the code is downloaded from the web page. This is not easy to find during local development.
The BUG of jQuery load () event processing. When an image is obtained from the browser cache, the error size is obtained.
The error code is:
(Error) Call the code to get the size immediately after HTML is added

Copy codeThe Code is as follows:
Var html = '';
Certificate ('{my_div'{.html (html );
Var width = $ ('# my_div img'). width (); // may return 0

(Error) Use jQuery's load () event for processing

Copy codeThe 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 correct method, using the JavaScript Image class:
Correct Method
Copy codeThe Code is as follows:
Var html = '';
Certificate ('{my_div'{.html (html );
Var ni = new Image ();
Ni. onload = function (){
Var width = ni. width;
}
Ni. src = img. attr (URL );

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.