Home > Web Front-end > JS Tutorial > Regarding the problem of using Jquery's height() and width() to calculate the width and height of dynamically inserted IMG tags_jquery

Regarding the problem of using Jquery's height() and width() to calculate the width and height of dynamically inserted IMG tags_jquery

WBOY
Release: 2016-05-16 18:14:14
Original
1593 people have browsed it

Let’s look at the phenomenon first:

Copy code The code is as follows:


<script> <br>$(document).ready(function() { <br>$("#cc").append("<div id='aa ' style='width:200px;height:200px;' /></div>"); <br>alert($("#aa").width()); <br>}); <br></script>

The result is: 200
All browsers get the correct result

Change the inserted element to IMG
Copy code The code is as follows:


< ;script>
$(document).ready(function() {
$("#cc").append("");
alert($("#aa").width());
});


(Note: the actual width of image1.jpg is 693)

The result is:
Opera:34
Firefox:0
IE:28
Chrome:0
Safari:0

Refresh with F5, the result is:
Firefox:693
IE:693
Opera:693
Chrome:0
Safari:0
Safari and Chrome are always 0.

It should be understood that the width and height of the image calculated when the image is not loaded or rendered is incorrect. There should be a cache after refreshing, so the result is correct, but why Chrome

and Safari are always 0? Moreover, IE and OPERA actually calculated an error value at the beginning.
Change it to the following:
Copy the code The code is as follows:


<script> <br>$(document).ready(function() { <br>$("#cc").append(" <img id='aa' src='http://www.jb51.net/images/logo.gif' />"); <br>window.setTimeout(function(){alert($("# aa").width()); },100); <br>}); <br></script>

Have you ever solved this problem or have more details about this problem? If you know Big Bird, please give me some advice.
Copy code The code is as follows:

$( document).ready(function() {
$("#cc").append("");
$("#aa").load( function(){
alert($("#aa").width()
}).attr("src", "http://www.jb51.net/images/logo.gif") ;
});
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