我怎样可以使用JavaScript中的css设置HTML元素的背景颜色?
我怎样可以使用JavaScript中的css设置HTML元素的背景颜色?
通常,CSS属性会通过将它们变成驼峰式而转换为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');
如果您将所有的样式等内容放在 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>
<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>
var element = document.getElementById('element_id');
element.style.backgroundColor = "color or color_code";
例子。
var element = document.getElementById('firstname');
element.style.backgroundColor = "green";//Or #ff55ff
element.style.background-color
不是有效的 JavaScript 代码。这就是为什么 CSS 属性被转换为 CamelCase 的原因。 - CrazyIvan1974KISS答案:
document.getElementById('element').style.background = '#DD00DD';
document.getElementByClass('element').style.background = '#DD00DD';
- MD Ashik$(".class").css("background","yellow");
$('#ID / .Class').css('background-color', '#FF6600');