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

Changing background-color of an element in CSS using Javascript

本文关键字:背景 颜色 元素 Javascript 更改 CSS 使用      更新时间:2023-09-26

基本上,我想通过单击按钮来更改CSS中JavaScript元素的背景颜色。

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

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

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

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

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

我是否正确理解您不想更改单个元素,而是更改 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>

只需将此部分作为"单击"事件处理程序分配给按钮即可设置。