使用Javascript更改CSS中元素的背景颜色

时间:2012-04-24 13:35:43

标签: javascript css

基本上我想通过点击按钮使用JavaScript更改CSS中元素的背景颜色。

到目前为止,我的CSS看起来像这样:

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

它需要动态变化为多种颜色的选择,只需要多个按钮即可(每种颜色都是不同颜色)。

3 个答案:

答案 0 :(得分:8)

完成: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;
}​

答案 1 :(得分:0)

vanilla-javascript方法是获取对元素的引用并使用style.backgroundColor来更改颜色:

例如,如果div的id为myBox,则使用

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

实例:http://jsfiddle.net/QWgcp/

顺便说一句,如果您正在做很多这样的操作框架,例如jQuery,那么在编写代码时会为您提供一些帮助。使用jQuery的相同功能会更简单:

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

答案 2 :(得分: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>

只需将此片段指定为“点击”事件处理程序即可设置。

相关问题