开发者

Jquery .width() returns 0 zero before appending the image to the browser

开发者 https://www.devze.com 2023-03-20 06:20 出处:网络
I\'m using jquery and i\'m trying to create a slideshow. Before i append the image, i shall know the Width of the image.

I'm using jquery and i'm trying to create a slideshow.

Before i append the image, i shall know the Width of the image. So i use .width() of jquery and .attr("width").

My code is as follows:

var attr_href = $next.attr('href'); /*returns the href of the image*/
var $item = $('<img src="'+attr_href+'" />'); 

//$item contains the image, the image is not displayed to the browser yet!!!

var itemWidth = $item.width();
alert(itemWidth); 
// --->  returns zero 0 in Mozilla and in IE

var itemWidth2 = $item.attr("width");
alert(itemWidth2);
//In Mozilla, the first time it returns 0.After the image is loaded, it returns the right Width
//In IE, always returns 0 zero !!!

//Now i have to append the photo and i have to use the right Width of the image!!!
开发者_开发百科var final_img = $('<img src="'+attr_href+'" width="'+itemWidth+'"/>');
$('.SlideShow').append(final_img);

So, i tried to use the .load() and i did:

var attr_href = $next.attr('href'); /*returns the href of the image*/
var $item = $('<img src="'+attr_href+'" />'); 

//$item contains the image, the image is not displayed to the browser yet!!!

$item.load(function  () {
    var WidthAfterLoading = $item.attr("width");
    var WidthAfterLoading2 = $item.width();

});

alert(WidthAfterLoading);  //returns "undefined" in both IE and Mozilla
alert(WidthAfterLoading2); //returns "undefined" in both IE and Mozilla

So, before i append the image to the browser, i shall know the right width of the image. But i get zero(0) and undefined.

Is there any other way, in order to take the right width of the image??

Thanks, in advance


Ah, I had the same problem before.

<img id="someImage"></img>

Then in your JQuery

$("#someImage").attr("src", "url/to/img").load(function() {  
    var width = $(this).width();
    // do stuff!
});

And a fiddle of course!


It is because the elements do not attach to the DOM tree
try to attach the elements to the DOM before invoking .width()

0

精彩评论

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

关注公众号