JavaScript中的CSS背景颜色

我如何设置使用JavaScript的HTML元素的CSS背景颜色?

一般来说,CSS属性被转换为JavaScript,使其驼峰没有任何破折号。 所以background-color变成了backgroundColor

 function setColor(element, color) { element.style.backgroundColor = color; } 

如果将所有样式等保存在CSS中,并且只需在JavaScript中设置/取消设置类名,则可能会发现代码更易于维护。

你的CSS显然是这样的:

 .highlight { background:#ff00aa; } 

然后在JavaScript中:

 element.className = element.className === 'highlight' ? '' : 'highlight'; 

var element = document.getElementById('element'); element.style.background = '#FF00AA';

或者,使用一个小的jQuery:

 $('#fieldID').css('background-color', '#FF6600'); 

将这个脚本元素添加到你的body元素中:

 <body> <script type="text/javascript"> document.body.style.backgroundColor = "#AAAAAA"; </script> </body> 
 var element = document.getElementById('element'); element.onclick = function() { element.classList.add('backGroundColor'); setTimeout(function() { element.classList.remove('backGroundColor'); }, 2000); }; 
 .backGroundColor { background-color: green; } 
 <div id="element">Click Me</div> 

KISS答案:

 document.getElementById('element').style.background = '#DD00DD'; 

您可以使用:

  <script type="text/javascript"> Window.body.style.backgroundColor = "#5a5a5a"; </script> 

你可以试试这个

 var element = document.getElementById('element_id'); element.style.backgroundColor = "color or color_code"; 

例。

 var element = document.getElementById('firstname'); element.style.backgroundColor = "green";//Or #ff55ff 

的jsfiddle

你可以用JQuery来做到这一点:

 $(".class").css("background","yellow"); 
 $('#ID / .Class').css('background-color', '#FF6600'); 

通过使用jQuery,我们可以定位元素的类或Id来应用CSS背景或任何其他样式

您可以使用

 $('#elementID').css('background-color', '#C0C0C0'); 
 $("body").css("background","green"); //jQuery document.body.style.backgroundColor = "green"; //javascript 

有很多方法,我认为这是非常简单和容易的

演示在Plunker

 $(".class")[0].style.background = "blue"; 

使用Javascript:

 document.getElementById("ID").style.background = "colorName"; //JS ID document.getElementsByClassName("ClassName")[0].style.background = "colorName"; //JS Class 

jQuery的:

 $('#ID/.className').css("background","colorName") // One style $('#ID/.className').css({"background":"colorName","color":"colorname"}); //Multiple style