Solution with value of jq width of 0 in chrome

  • 2020-03-30 03:07:17
  • OfStack

http://photo.163.com/shixiaojian089/train/28002 this is a photo album, netease, try doing it after see to.

In my method, I needed to get the width of each photo, so it was natural to use the width() method of jq. Running ff and ie was fine, but on chrome, it was.

Using alert, we found that the width method in chrome was 0. In this case, the image was not loaded properly when the script was running. The problem should be $(function(){}); Because this method only requires that the dom be loaded and run. So I'm going to do it under onload, and sure enough that works. This is obviously not a good idea, since running under onload doesn't run the script until the entire file is loaded.

After a search on the Internet, I found that this guy also encountered the same problem. In the comments, there is a solution, which can be referred to as:

Used where you want to get the width and height of the image
 
$img.load(function(){ 
var img_h = $img.height(); 
var img_w = $img.width(); 
} 

So you can still use $(function(){}); Call the load method on the image object where the image is needed to avoid waiting for the entire file content to load.

Related articles: