简体   繁体   中英

width returning 0 in jquery

i have some jquery script which runs after the window has loaded

$(window).load( function() {
   $('.picture a img').each(function(index) {
       $(this).height(280);
       if ($(this).width() > $(this).height()) {
          alert("yes");
       } else {
          alert("no");
       }

   });
});

i always get a "no" from this when i know some of the images should be a "yes". When i trace the script in chrome i noticed that the $(this).width() always returns a 0. ive googled around and some suggestions were that the images havent loaded but here ive used the window.load method which i thought should run once everything has loaded. any ideas??

thanks for any help in advance

Chrome is weird about image widths. I noticed then when building a jQuery photo gallery. If your image width is not specifically set in the tag, chrome will return 0. FF, and IE will figure out the width, but chrome will not. Try actually setting the width and see if you get the desired result then.

<img width="200" src="..." />

You need to run your code when the image is loaded, the following code should work:

$(window).load( function() {
   $('.picture a img').load( function() {
       $(this).height(280);
       if ($(this).width() > $(this).height()) {
          alert("yes");
       } else {
          alert("no");
       }
   });
}); 

note that every DOM element that have some kind of web resource associated to (window, img, iframe) respond to.load() event.

try

if ($(this).attr("width") > $(this).attr("height")) {

try adding a load event on the image, so it will only execute when the image is fully loaded.

$(window).load( function() {
  $('.picture a img').each(function(index) {
     $(this).bind('load', function () {
       $(this).height(280);
       if ($(this).width() > $(this).height()) {
          alert("yes");
       } else {
          alert("no");
       }
     })
   });
});

you can also try checking this.complete on the image object

I just wanted to add that you should also ensure that your image is actually a visible element. I've had plenty of issues in the past trying to measure visible:hidden or display:none elements. If you are indeed attempting to measure a hidden element, you can get past it by doing something like

var width = $('img').show().width();
$('img').hide();

Now that code is incredibly vague, but it gives you my thought behind visibility flashing.

The correct method to use, to run your scripts after the dom has finished loading, is:

$(document).ready(function() { /*your code here*/ });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM