JavaScript를 사용하여 HTML의 CSS 배경색을 설정하는 방법


답변:


155

일반적으로 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');

3
분명히 따옴표 안에 있어야하는 색상을 추가하고 싶습니다. element.style.backgroundColor = "color"; 예 : element.style.backgroundColor = "orange"; 우수한 답변
Catto jul.

Selenium 테스트에서 : ((IJavaScriptExecutor) WebDriver) .ExecuteScript ( "arguments [0] .style.background = 'yellow';", webElement);
nexoma

@Catto이 경우 색상은 함수에 대한 인수이므로 따옴표로 묶어서는 안됩니다. 그러나 일반적으로 색상을 설정하면 JS에서 큰 따옴표가 필요하다는 것이 옳습니다.
Bharat Mallapur

29

CSS에서 모든 스타일 등을 유지하고 JavaScript에서 클래스 이름을 설정 / 설정 해제하면 코드가 더 유지 관리하기 쉽다는 것을 알 수 있습니다.

CSS는 분명히 다음과 같습니다.

.highlight {
    background:#ff00aa;
}

그런 다음 JavaScript에서 :

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

2
나는 그것을 어디에 넣을지 분명하다고 말하고 싶다.-당신이 바꾸고 싶은 HTML 뒤에 어디든지.
TeeJay 2014 년

1
이것은 대부분의 경우에 유효하지만 색상 (또는 속성)이 구성에 정의되거나 사용자가 입력 한 경우에는 가능한 모든 색상에 대해 CSS 클래스를 만들 수 없습니다.)
Juan Mendes

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

20

또는 약간의 jQuery를 사용합니다.

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

OP가 Javascript를 요청했기 때문에 가능성이 가장 높습니다.)
Lodder

7

다음 스크립트 요소를 본문 요소에 추가하십시오.

<body>
  <script type="text/javascript">
     document.body.style.backgroundColor = "#AAAAAA";
  </script>
</body>

6

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>


4

당신은 이것을 시도 할 수 있습니다

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


1
element.style.background-color유효한 JavaScript가 아닙니다. 이것이 CSS 속성이 CamelCase로 변환되는 이유입니다.
CrazyIvan1974 2015 년


3

키스 답변 :

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

수업을 위해 어떻게 할 수 있습니까?
Vignesh Subramanian 2015

수업 용document.getElementByClass('element').style.background = '#DD00DD';
MD Ashik 2016

3

당신이 사용할 수있는:

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

3
$("body").css("background","green"); //jQuery

document.body.style.backgroundColor = "green"; //javascript

방법이 너무 많아서 아주 쉽고 간단하다고 생각합니다

Plunker 데모


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

jquery를 사용하여 요소의 클래스 또는 ID를 대상으로 CSS 배경 또는 기타 스타일을 적용 할 수 있습니다.


1

당신이 사용할 수있는

$('#elementID').css('background-color', '#C0C0C0');

이 JQuery와 자바 스크립트 아니다
인 Vignesh Subramanian

jQuery를이 @vignesh 입니다 -__- 자바 스크립트
탔을

@Novocaine jQuery는 JavaScript를 사용하여 작성되었습니다. 하지만 $는 jQuery 라이브러리를 포함하지 않으면 작동하지 않습니다.)
Vignesh Subramanian

0

자바 스크립트 :

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

0

CSS 변경 HTMLElement

JavaScript로 대부분의 CSS 속성을 변경할 수 있습니다. 다음 문을 사용합니다.

document.querySelector(<selector>).style[<property>] = <new style>

여기서 <selector>, <property>, <new style>모두 String객체.

일반적으로 스타일 속성은 CSS에서 사용되는 실제 이름과 동일한 이름을 갖습니다. 그러나 한 단어 이상이있을 때마다 낙타 케이스가됩니다. 예를 들어 다음과 같이 background-color변경됩니다.backgroundColor . .

다음 명령문은의 배경을 #container빨간색으로 설정합니다 .

documentquerySelector('#container').style.background = 'red'

다음은 0.5 초마다 상자 색상을 변경하는 빠른 데모입니다.

colors = ['rosybrown', 'cornflowerblue', 'pink', 'lightblue', 'lemonchiffon', 'lightgrey', 'lightcoral', 'blueviolet', 'firebrick', 'fuchsia', 'lightgreen', 'red', 'purple', 'cyan']

let i = 0
setInterval(() => {
  const random = Math.floor(Math.random()*colors.length)
  document.querySelector('.box').style.background = colors[random];
}, 500)
.box {
  width: 100px;
  height: 100px;
}
<div class="box"></div>


여러 CSS 변경 HTMLElement

예를 들어 클래스 이름이있는 모든 요소의 배경색을 만드는 것과 같이 둘 이상의 요소에 CSS 스타일을 적용한다고 가정 해보십시오 box lightgreen. 그런 다음 다음을 수행 할 수 있습니다.

  1. 요소를 선택하고 destructuring 구문을 사용하여 .querySelectorAll객체에서 래핑을 풉니 다 .Array

    const elements = [...document.querySelectorAll('.box')]
  2. 배열을 반복 .forEach하고 각 요소에 변경 사항을 적용합니다.

    elements.forEach(element => element.style.background = 'lightgreen')

다음은 데모입니다.

const elements = [...document.querySelectorAll('.box')]
elements.forEach(element => element.style.background = 'lightgreen')
.box {
  height: 100px;
  width: 100px;
  display: inline-block;
  margin: 10px;
}
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>


다른 방법

한 요소의 여러 스타일 속성을 두 번 이상 변경하려면 다른 방법을 사용할 수 있습니다. 대신이 요소를 다른 클래스에 연결합니다.

CSS에서 미리 스타일을 준비 할 수 있다고 가정하면 classList요소 에 액세스 하고 toggle함수를 호출하여 클래스를 전환 할 수 있습니다 .

document.querySelector('.box').classList.toggle('orange')
.box {
  width: 100px;
  height: 100px;
}

.orange {
  background: orange;
}
<div class='box'></div>


JavaScript의 CSS 속성 목록

전체 목록은 다음과 같습니다.

alignContent
alignItems
alignSelf
animation
animationDelay
animationDirection
animationDuration
animationFillMode
animationIterationCount
animationName
animationTimingFunction
animationPlayState
background
backgroundAttachment
backgroundColor
backgroundImage
backgroundPosition
backgroundRepeat
backgroundClip
backgroundOrigin
backgroundSize</a></td>
backfaceVisibility
borderBottom
borderBottomColor
borderBottomLeftRadius
borderBottomRightRadius
borderBottomStyle
borderBottomWidth
borderCollapse
borderColor
borderImage
borderImageOutset
borderImageRepeat
borderImageSlice
borderImageSource  
borderImageWidth
borderLeft
borderLeftColor
borderLeftStyle
borderLeftWidth
borderRadius
borderRight
borderRightColor
borderRightStyle
borderRightWidth
borderSpacing
borderStyle
borderTop
borderTopColor
borderTopLeftRadius
borderTopRightRadius
borderTopStyle
borderTopWidth
borderWidth
bottom
boxShadow
boxSizing
captionSide
clear
clip
color
columnCount
columnFill
columnGap
columnRule
columnRuleColor
columnRuleStyle
columnRuleWidth
columns
columnSpan
columnWidth
counterIncrement
counterReset
cursor
direction
display
emptyCells
filter
flex
flexBasis
flexDirection
flexFlow
flexGrow
flexShrink
flexWrap
content
fontStretch
hangingPunctuation
height
hyphens
icon
imageOrientation
navDown
navIndex
navLeft
navRight
navUp>
cssFloat
font
fontFamily
fontSize
fontStyle
fontVariant
fontWeight
fontSizeAdjust
justifyContent
left
letterSpacing
lineHeight
listStyle
listStyleImage
listStylePosition
listStyleType
margin
marginBottom
marginLeft
marginRight
marginTop
maxHeight
maxWidth
minHeight
minWidth
opacity
order
orphans
outline
outlineColor
outlineOffset
outlineStyle
outlineWidth
overflow
overflowX
overflowY
padding
paddingBottom
paddingLeft
paddingRight
paddingTop
pageBreakAfter
pageBreakBefore
pageBreakInside
perspective
perspectiveOrigin
position
quotes
resize
right
tableLayout
tabSize
textAlign
textAlignLast
textDecoration
textDecorationColor
textDecorationLine
textDecorationStyle
textIndent
textOverflow
textShadow
textTransform
textJustify
top
transform
transformOrigin
transformStyle
transition
transitionProperty
transitionDuration
transitionTimingFunction
transitionDelay
unicodeBidi
userSelect
verticalAlign
visibility
voiceBalance
voiceDuration
voicePitch
voicePitchRange
voiceRate
voiceStress
voiceVolume
whiteSpace
width
wordBreak
wordSpacing
wordWrap
widows
writingMode
zIndex

0

간단한 js로 해결할 수 있습니다.

document.getElementById("idName").style.background = "blue";

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

이 질문에 대한 정답이 충분하며이 답변은 다른 답변보다 더 나은 것을 제공하지 않습니다.
탔을

Novocaine이 말했듯이 여기에는 많은 답변이 있습니다. 그러나 앞으로 코드가 수행하는 작업과 문제를 해결하는 이유에 대한 설명을 추가하기 위해 게시물을 편집하는 것을 고려하십시오. 대부분 코드 만 포함하는 답변 (작동 중이더라도)은 일반적으로 OP가 문제를 이해하는 데 도움이되지 않습니다.
SuperBiasedMan
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.