Programing

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

crosscheck 2020. 8. 9. 09:46
반응형

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


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

JSFIDDLE


JQuery로 할 수 있습니다.

$(".class").css("background","yellow");

키스 답변 :

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

당신이 사용할 수있는:

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

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

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

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

Plunker 데모


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

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


당신이 사용할 수있는

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

자바 스크립트 :

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

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

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

참고 URL : https://stackoverflow.com/questions/3319/how-to-set-css-background-color-of-html-using-javascript

반응형