开发者

width() not returning a value

I have an image in a page that I am trying to get the width of.

<img class="zoomerIcon" src="zoo开发者_如何学编程mer.png" />

So I'm trying to get the width like this.

var imageWidth = $('.zoomerIcon').width();

However the value is 0 unless I set the width property in the tag.

Does width() only return a width greater than 0 if it's manually set in the property? You can see the whole script here.

http://www.wantedcreative.com/development/zoomer/index.html

Thanks


Update

Sorry, I should have looked at your source first. Here is how you need to change your code. The important thing to realize, is you can't get the width until the image has fully loaded. That is why I use a load event callback to retrieve the widths:

// Create the img element, add a load handler, then append it to the body
var $img = $('<img class="zoomIcon" alt="zoom icon" />').load(function(e){
  // get icon image properties for use with animation
  var imageWidth = $(this).width();
  var imageHeight = $(this).height();

  // ... any code that uses these variables needs to go in here ...

}).attr('src', zoomImage).appendTo( document.body );

Original Answer: This is general information.

You are probably putting this code in document.ready which will try to retrieve the width before the image has loaded. Try this instead:

$(window).load(function(){
   var imageWidth = $(".zoomer").width();
   alert( imageWidth ); // Should be correct
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜