2013-08-18 23 views
1

我有這樣的JS(也使用jQuery):根據追加到div的圖像,並計算出它的高度並設置爲CSS

$(".article_big_photo").click(function() { 
    $('#screen').css({ opacity: 0.5, 'width':$(document).width(),'height':$(document).height()}); 
    $('#screen').show(); 
    $('#article_photo_modal').show(); 
    var image = document.createElement("img"); 
    var url = $(this).attr("b_img"); 
    $(image).attr("src", url); 
    $('#article_photo_modal').css({ 'margin':$(image).height()+" 0 0 -270px"}); 
    $('.photo_innerbox').append(image); 
    }); 

但是當我試圖讓圖像的大小,我看到它的高度(我代碼)爲0.

如何追加,獲取和設置爲CSS圖像大小?我的代碼沒有工作

+0

可能重複[?獲取真實圖像的寬度和高度的JavaScript在Safari /鉻(http://stackoverflow.com/questions/318630/get-real - 圖像寬度和高度與 - JavaScript的在野生動物園鉻) – raam86

回答

3

你需要獲取的高度圖像加載

$(".article_big_photo").click(function() { 
    $('#screen').css({ opacity: 0.5, 'width':$(document).width(),'height':$(document).height()}); 
    $('#screen').show(); 
    $('#article_photo_modal').show(); 
    var image = document.createElement("img"); 
    var url = $(this).attr("b_img"); 
    $(image).attr("src", url); 
    $(image).load(function(){ 
     $('#article_photo_modal').css({ 'margin':$(image).height() +" 0 0 -270px"}); 
    }); 
    $('.photo_innerbox').append(image); 
}); 
1

後像阿倫說,你必須獲取圖像加載後的高度。

你也可以試試這個:

var img = new Image(); 
img.src = $(this).attr("b_img"); 
img.height; 
相關問題