2014-10-05 36 views
1

基本上我希望用戶能夠點擊和更改背景,併爲那裏有多個背景,爲特定的div。更改div背景圖像,JS在鉻但不是IE或Firefox的作​​品?

這在Google Chrome中完美工作,但不在IE或Firefox中。

HTML:

<div id="palette"> 
<div class="lightblue"></div> 
<div class="gold"></div> 
<div class="aqua"></div> 
</div> 

<div id="primary"> 
</div> 

CSS:

#palette { 
border: 2px solid white; 
width: 25px; 
} 

#palette div { 
height: 25px; 
width: 25px; 
} 

.lightblue { 
background: lightblue url(http://www.textureking.com/content/img/stock/big/DSC_4279.JPG); 
} 

.gold { 
background: gold url(http://www.textureking.com/content/img/stock/big/DSC_4287.JPG); 
} 

.aqua { 
background: aqua url(http://www.textureking.com/content/img/stock/big/DSC_4274.JPG); 

}

JS:

$(document).ready(function() { 
// attach onclick event to your palette colors 
$('#palette div').on('click', function() { 
    // get background of selected palette color 
    var bg = $(this).css('background'); 
    // change the background of the body 
    $('#primary').css({ 'background': bg }); 
}); 
}); 

http://jsfiddle.net/KNutQ/1/

它沒有顯示任何錯誤和其他JavaScript運行,所以我不確定問題是什麼。

如果它是很容易解決,請留下一個答案,如果沒有,我會這樣試試:http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_style_backgroundimage

+0

嗯或許可以創建一個cookie來記住他們選擇的背景? – amuletts 2014-10-05 23:09:04

回答

0

根據CSS規範得到一個速記的計算樣式不應返回任何東西。您需要按照以下所述列出各個屬性。

也許CSS規範或Chrome將在未來發生變化,但目前Firefox和IE的行爲是正確的。

$(document).ready(function() { 
    // attach onclick event to your palette colors 
    $('#palette div').on('click', function() { 
     // get background of selected palette color 
     var backgrounds = $(this).css(['background-color','background-image', 'background-repeat', 'background-attachment', 'background-position']); 
     // change the background of the body 
     $('body').css(backgrounds); 
    }); 
}); 
相關問題