문제

는 방법을 설정할 수 있습니 CSS 배경 색상의 HTML 를 사용하여 요소 JavaScript?

도움이 되었습니까?

해결책

일반적으로,CSS 속성이로 변환하여 자바스크립트들을 서로 다른 없이 대시입니다.그래서 background-colorbackgroundColor.

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

다른 팁

당신이 찾을 수 있습니다 당신의 코드의 유지 관리성을 향상시켜준을 유지하는 경우 귀하의 모든 스타일 등등.CSS 및 설정/해제 클래스 이름에서 JavaScript.

CSS 것이 분명히 같은 것:

.highlight {
    background:#ff00aa;
}

그 다음에 자바스크립트:

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>
$('#ID / .Class').css('background-color', '#FF6600');

를 사용하여 jquery 우리 대상이 될 수 있는 요소의 클래스 또는 Id 를 적용 css 배경 또는 다른 스타일

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

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

이렇게 많은 방법에 있는 그것을 생각하는 것은 매우 쉽고 간단하

데모 Plunker

당신이 사용할 수 있는

$('#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

당신의 대부분을 변경할 수 있습니다 CSS 속성을 자바스크립트와 이 문을 사용하여:

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

<selector>, <property>, <new style> 은 모든 String 체입니다.

일반적으로,스타일의 숙박 시설 같은 이름으로 실제 사용하는 이름에서 CSS.그러나 때마다 거기에 더 많은 중 하나는 단어,그것은 낙타의 경우:예를 들어 background-color 으로 변경된 backgroundColor.

다음과 같은 문의 배경을 설정 #container 색상에 빨간색:

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

여기에 빠른 데모의 색상을 변경하자는 모든 0.5s:

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. 요소를 선택과 .querySelectorAll 와 풀에서 그들을체 Array선언 및 구문:

    const elements = [...document.querySelectorAll('.box')]
    
  2. 루프를 통해 배열 .forEach 와 적용을 변경하는 각 요소:

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

여기에 demo:

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>


목록에 CSS 속성 JavaScript

여기에는 완전한 목록:

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";
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top