2011-03-23 68 views
3

我試圖挽救一個元素的背景圖像,刪除它,然後也許添加回來後jQuery的 - CSS(「背景圖片」,變量)不工作:(

var current_bg_image = $("#div").css("background-image"); 
if(something){ 
    $("#div").css("background-image", "none"); 
}else{ 
    $("#div").css("background-image", current_bg_image); // not working... 
} 

其中背景圖像應該加回不工作... 但是,如果我改變current_bg_image"url(something.jpg)"它的工作原理,似乎CSS()不使用變量的一部分?

回答

4

你代碼對我使用jQuery 1.5.1很好,我相信一旦將背景圖像值保存到current_bg_image就是圖像的完整路徑,所以請嘗試使用Firebug或alert(current_bg_image)讀取該值,並確保它是您認爲應該是的。

+0

TX,實際問題是,'VAR current_bg_image = $( 「#DIV」),CSS( 「背景圖片」);'。每次調用函數時都運行,我把它放在外面,現在它確定:) – Alex 2011-03-23 06:49:42

10

有同樣的問題,這個解決:

var id = $(this).attr("src"); //alert(id); $('#div').css({'background-image': 'url(' + id + ')', });