如何使用JavaScript设置HTML的CSS背景颜色

Gat*_*ler 109 javascript css background-color

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

Dav*_*ier 152

通常,CSS属性通过使它们成为没有任何破折号的camelCase而转换为JavaScript.因此background-color变得backgroundColor.

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

// where el is the concerned element
var el = document.getElementById('elementId');
setColor(el, 'green');
Run Code Online (Sandbox Code Playgroud)

  • 我想添加颜色显然需要在引号element.style.backgroundColor ="color"; 例如 - element.style.backgroundColor ="orange"; 很好的答案 (3认同)

Ian*_*ley 29

如果您在CSS中保留所有样式等,并且只是在JavaScript中设置/取消设置类名,您可能会发现代码更易于维护.

你的CSS显然是这样的:

.highlight {
    background:#ff00aa;
}
Run Code Online (Sandbox Code Playgroud)

然后在JavaScript中:

element.className = element.className === 'highlight' ? '' : 'highlight';
Run Code Online (Sandbox Code Playgroud)

  • 我会说它显而易见的地方 - 在你要改变的HTML之后的任何地方. (2认同)

tag*_*s2k 24

var element = document.getElementById('element');
element.style.background = '#FF00AA';
Run Code Online (Sandbox Code Playgroud)


Wal*_*ess 20

或者,使用一点点jQuery:

$('#fieldID').css('background-color', '#FF6600');
Run Code Online (Sandbox Code Playgroud)


jam*_*iss 7

将此脚本元素添加到body元素:

<body>
  <script type="text/javascript">
     document.body.style.backgroundColor = "#AAAAAA";
  </script>
</body>
Run Code Online (Sandbox Code Playgroud)


小智 6

var element = document.getElementById('element');

element.onclick = function() {
  element.classList.add('backGroundColor');
  
  setTimeout(function() {
    element.classList.remove('backGroundColor');
  }, 2000);
};
Run Code Online (Sandbox Code Playgroud)
.backGroundColor {
    background-color: green;
}
Run Code Online (Sandbox Code Playgroud)
<div id="element">Click Me</div>
Run Code Online (Sandbox Code Playgroud)


Aja*_*pta 5

你可以试试这个

var element = document.getElementById('element_id');
element.style.backgroundColor = "color or color_code";
Run Code Online (Sandbox Code Playgroud)

例子。

var element = document.getElementById('firstname');
element.style.backgroundColor = "green";//Or #ff55ff
Run Code Online (Sandbox Code Playgroud)

JSFIDDLE