JavaScript를 사용하여 HTML 요소의 CSS 배경색을 어떻게 설정할 수 있습니까?
답변
일반적으로 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');
답변
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
