2011-07-12 10 views
1

jqueryを使用していますが、スライドショーを作成しようとしています。私は画像を追加する前にJquery .width()は、画像をブラウザに追加する前に0を返します。

、私は画像の幅を知っているものとします。 だから私は。幅()のjqueryと.attr( "幅")を使用します。次のように

マイコードがある:だから

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); 

、私は.LOAD()を使用しようとした私でした:

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 

だから、私は追加する前に画像をブラウザに送れば、画像の正しい幅がわかるはずです。 しかし、私はゼロ(0)と定義されていません。

イメージの右の幅を取るために他の方法はありますか?

おかげで、事前

+0

はありませんので、 'width'属性 – Phil

+0

ありません)(.width呼び出す前に、DOMに要素をアタッチする
試みを添付し、.ATTRしていないからです") 間違っている? – programmer

+0

私はお詫びします、私は '$ item'が' a'タグであると考えていました。 – Phil

答えて

7

ああ、私は前に同じ問題を抱えていました。

あなたのjQueryの

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

そしてもちろんのfiddleで次に

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

+0

おかげでまだ画像がロードされていても0のゼロが得られますが、私は再びゼロになります。私は何をすればいいのか分かりません... – programmer

+1

コードをフィドルで試してみてください。何が起こっているのか見てください:) – vinceh

0

要素は「(幅をDOMツリーに

関連する問題