2012-08-02 48 views
0

這是我得到它已被追加之後的jQuery .append元素的性質

var path = $('#sprite').css('background-image').replace('url', '').replace('(', '').replace(')', '').replace('"', '').replace('"', '') 
var tempImg = '<img id="tempImg" src="' + path + ' "/>'; 
$('body').append(tempImg); 
alert($('#tempImg').width()); 

結果是0,但如果我去到一個控制檯,然後輸入$('#tempImg').width(),我們得到正確的寬度。

那麼,什麼似乎是追加只是「裝」的代碼執行後,我需要用我的代碼項目已被追加後,有沒有辦法?

+0

你需要等待圖像負載,有幾個答案,以及如何做到這一點很好的代碼示例。 – adeneo 2012-08-02 19:05:51

+0

你什麼時候調用這個代碼?你試過用$(function(){...})來包裝它。 ? – Vlad 2012-08-02 19:05:53

+0

的代碼被稱爲成$(文件)。就緒(函數(){}); – steps 2012-08-02 19:25:30

回答

0

多虧了這裏的一些意見和答案我取得了成功實現我的目標

frame_width = $('#sprite').width(); 

var path = $('#sprite').css('background-image').replace('url', '').replace('(', '').replace(')', '').replace('"', '').replace('"', '') 
var tempImg = '<img id="tempImg" src="' + path + ' "/>'; 
    $('body').append(tempImg); 
    $('#tempImg').load(function(){ 
     alert($("#tempImg").width()); 
    }); 

這個工作,並通知了正確的價值 謝謝大家

0

必須等待加載圖像。

var path = $('#sprite').css('background-image').replace('url', '').replace('(', '').replace(')', '').replace('"', '').replace('"', ''); 
var tempImg = new Image(); 
tempImg.id = "tempImg"; 
$(tempImg).load(function(){ 
    $('body').append(tempImg); 
    alert($(tempImg).width()); 
}); 
tempImg.src = path; 
+0

它沒有工作,但我所看到的,你沒有在tempImg創建使用路徑值,我不明白你做了什麼。 – steps 2012-08-02 19:29:04

+0

綁定load事件後,路徑被設置爲src屬性。它是如何工作的?它什麼都不做?控制檯中是否顯示錯誤或警告?圖像是否被附加了?警報是否警告錯誤的值? – 2012-08-02 19:30:31

+0

警報沒有任何警覺,但使用我實現了我的目標負載的功能,謝謝 – steps 2012-08-02 19:33:07