2012-04-24 331 views
2

基本上,我想通過點擊一個按鈕來改變CSS中元素的背景顏色。使用Javascript更改CSS中元素的背景顏色

到目前爲止,我的CSS看起來是這樣的:

div.box { 
    width:100px; 
    height:100px; 
    background-color:#FF2400; 
} 

它需要動態變化,以幾個顏色的選擇,只是多個按鈕會做(各爲不同的顏色)。

+0

你可以使用jQuery:http://api.jquery.com/css/,或者使用DOM來改變這個樣式,例如:document.body.yourelementname.style.backgroundColor =「#FECE03」 – renard 2012-04-24 13:41:10

+0

你在這找到有用的東西? – iambriansreed 2012-04-24 14:16:41

回答

0

香草JavaScript的方式做,這是去的元素的引用,並使用style.backgroundColor來改變顏色:

例如,如果DIV有myBox一個id,你會使用

document.getElementById("myBox").style.backgroundColor="#000000"; // change to black 

活生生的例子:http://jsfiddle.net/QWgcp/

順便說一句,如果你做了很多這樣的操作框架,如jQuery的爲您提供編寫代碼一些幫助。使用jQuery相同的功能將是一個有點簡單:

$('#myBox').css('background-color','#000000'); 
+0

刪除我的DV,因爲你有你的小提琴。 OP要求按鈕。 – iambriansreed 2012-04-24 13:51:37

6

完成:http://jsfiddle.net/iambriansreed/zmtU4/

更新爲非jQuery的。

HTML

<div id="box"></div><div id="box"></div> 

<button type="button" onclick="button_click('red');">Red</button> 
<button type="button" onclick="button_click('blue');">Blue</button> 
<button type="button" onclick="button_click('green');">Green</button> 
<button type="button" onclick="button_click('yellow');">Yellow</button> 
<button type="button" onclick="button_click('purple');">Purple</button>​ 

純JavaScript

function button_click(color){ 
    document.getElementById("box").style.backgroundColor=color; 
}​ 
+0

-1的任何原因? – iambriansreed 2012-04-24 13:43:34

+0

-1 for jsfiddle only answer。 -1僅適用於未標記爲「jQuery」的問題的jQuery解決方案。 +1一個體面的jsfiddle – Jamiec 2012-04-24 13:43:41

+0

@Jamiec純JS解決方案。包括代碼。等待你的+1。 – iambriansreed 2012-04-24 13:50:35

0

難道我理解正確的,你不希望改變單一的元素,而是CSS規則代替,因此,所有匹配的元素會受到影響?下面是一個例子,如何動態地在你的榜樣改變風格,以藍色:

<html> 
<head> 
<style> 
div.box{ 
    width:100px; 
    height:100px; 
    background-color:#FF2400; 
} 
</style> 
<script> 
    var sheet = document.styleSheets[0] // Of course if you have more than one sheet you'll have to find it among others somehow 
    var rulesList = sheet.cssRules || sheet.rules // some older browsers have it that way 
    var rule = rulesList[0] // same for rules - more than one and you'll have to iterate to find what you need 
    rule.style.backgroundColor = 'blue' // and voila - both boxes are now blue 
</script> 
</head> 
<body> 
<div class="box"></div> 
<div class="box"></div> 
</body> 
</html> 

剛分配這片如「點擊」事件處理程序按鈕,你設置。