Como posso definir a cor de fundo CSS de um elemento HTML usando JavaScript?
Como posso definir a cor de fundo CSS de um elemento HTML usando JavaScript?
Respostas:
Em geral, as propriedades CSS são convertidas em JavaScript tornando-as camelCase sem travessões. Assim background-color
se torna backgroundColor
.
function setColor(element, color)
{
element.style.backgroundColor = color;
}
// where el is the concerned element
var el = document.getElementById('elementId');
setColor(el, 'green');
Você pode achar que seu código é mais sustentável se você mantiver todos os seus estilos, etc. em CSS e apenas definir / remover nomes de classe em JavaScript.
Seu CSS seria obviamente algo como:
.highlight {
background:#ff00aa;
}
Depois, em JavaScript:
element.className = element.className === 'highlight' ? '' : 'highlight';
Ou, usando um pouco de jQuery:
$('#fieldID').css('background-color', '#FF6600');
Adicione este elemento de script ao seu elemento de corpo:
<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>
Você pode tentar isso
var element = document.getElementById('element_id');
element.style.backgroundColor = "color or color_code";
Exemplo.
var element = document.getElementById('firstname');
element.style.backgroundColor = "green";//Or #ff55ff
element.style.background-color
não é JavaScript válido. É por isso que as propriedades CSS são convertidas em CamelCase.
Resposta do KISS:
document.getElementById('element').style.background = '#DD00DD';
document.getElementByClass('element').style.background = '#DD00DD';
$("body").css("background","green"); //jQuery
document.body.style.backgroundColor = "green"; //javascript
existem tantas maneiras que acho muito fácil e simples
$('#ID / .Class').css('background-color', '#FF6600');
Usando jquery podemos direcionar a classe ou Id do elemento para aplicar o fundo css ou qualquer outro estilo
você pode usar
$('#elementID').css('background-color', '#C0C0C0');
Javascript:
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
HTMLElement
Você pode alterar a maioria das propriedades CSS com JavaScript, use esta instrução:
document.querySelector(<selector>).style[<property>] = <new style>
onde <selector>
, <property>
, <new style>
são todos String
objetos.
Normalmente, a propriedade de estilo terá o mesmo nome que o nome real usado em CSS. Mas sempre que houver mais de uma palavra, será o caso de camelo: por exemplo, background-color
é alterado com backgroundColor
.
A seguinte declaração definirá o fundo de #container
para a cor vermelha:
documentquerySelector('#container').style.background = 'red'
Aqui está uma rápida demonstração mudando a cor da caixa a cada 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>
HTMLElement
Imagine que você gostaria de aplicar estilos CSS a mais de um elemento, por exemplo, fazer a cor de fundo de todos os elementos com o nome da classe box
lightgreen
. Então você pode:
selecione os elementos .querySelectorAll
e os desembrulhe em um objeto Array
com a sintaxe de desestruturação :
const elements = [...document.querySelectorAll('.box')]
faça um loop sobre a matriz com .forEach
e aplique a alteração a cada elemento:
elements.forEach(element => element.style.background = 'lightgreen')
Aqui está a demonstração:
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>
Se você deseja alterar várias propriedades de estilo de um elemento mais de uma vez, você pode considerar o uso de outro método: vincule este elemento a outra classe.
Supondo que você possa preparar os estilos de antemão em CSS, você pode alternar as classes acessando o classList
do elemento e chamando a toggle
função:
document.querySelector('.box').classList.toggle('orange')
.box {
width: 100px;
height: 100px;
}
.orange {
background: orange;
}
<div class='box'></div>
Aqui está a lista completa:
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
Um simples js pode resolver isso:
document.getElementById("idName").style.background = "blue";
$(".class")[0].style.background = "blue";