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

3
基本上,我想要在单击按钮时使用JavaScript更改CSS中元素的背景颜色。
到目前为止,我的CSS看起来像这样:
div.box {
    width:100px;
    height:100px;
    background-color:#FF2400;
}

需要动态更改为几种颜色的选择,只需使用多个按钮即可(每个按钮都是不同的颜色)。


你可以使用 jQuery: http://api.jquery.com/css/,或者例如以下方式使用 DOM 更改样式: document.body.yourelementname.style.backgroundColor =“#FECE03” - renard
你在这里找到了有用的东西吗? - iambriansreed
3个回答

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 对于仅在jsfiddle上回答的问题。 -1 对于未标记为“jQuery”的问题,仅提供jQuery解决方案。 +1 对于一个不错的jsfiddle。 - Jamiec
@Jamiec 纯JS解决方案。包含代码。等待您的+1。 - iambriansreed
我没有给你的答案点踩,我只是解释了为什么你(很可能)被点踩了。我会点赞来平衡一下。 - Jamiec

1

在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');

已经在你的fiddle中删除了我的DV。问题提出者要求按钮。 - iambriansreed

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>

只需将此代码片段分配为按钮的“click”事件处理程序,您就可以完成设置。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接