2012-04-24 125 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> 

刚分配这片如“点击”事件处理程序按钮,你设置。