Como definir a cor do fundo do CSS do HTML usando JavaScript
-
08-06-2019 - |
Pergunta
Como posso definir a cor do fundo do CSS de um elemento HTML usando JavaScript?
Solução
Em geral, as propriedades CSS são convertidos para JavaScript, fazendo com que eles camelCase sem quaisquer traços.Então, background-color
torna-se backgroundColor
.
function setColor(element, color)
{
element.style.backgroundColor = color;
}
Outras dicas
Você pode encontrar o seu código é mais fácil de se manter todos os seus estilos, etc.no CSS e apenas definido / indefinido de nomes de classe em JavaScript.
O CSS seria, obviamente, algo como:
.highlight {
background:#ff00aa;
}
Em seguida, em JavaScript:
element.className = element.className === 'highlight' ? '' : 'highlight';
var element = document.getElementById('element');
element.style.background = '#FF00AA';
Ou, usando um pouco de jQuery:
$('#fieldID').css('background-color', '#FF6600');
Adicionar este script elemento para o elemento body:
<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
Você pode fazer com JQuery:
$(".class").css("background","yellow");
BEIJO Resposta:
document.getElementById('element').style.background = '#DD00DD';
Você pode usar:
<script type="text/javascript">
Window.body.style.backgroundColor = "#5a5a5a";
</script>
$('#ID / .Class').css('background-color', '#FF6600');
Usando jquery podemos segmentar o elemento de classe ou Id para aplicar fundo do css ou qualquer outro stylings
$("body").css("background","green"); //jQuery
document.body.style.backgroundColor = "green"; //javascript
assim, existem muitas maneiras eu acho que é muito fácil e simples
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
Alterar o CSS de um 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
os objetos.
Geralmente, o estilo de propriedade terá o mesmo nome como o nome real utilizado no CSS.Mas sempre há mais que uma palavra, ele vai ser camelo caso:por exemplo background-color
é alterado com backgroundColor
.
A instrução a seguir irá definir o plano de fundo de #container
para a cor vermelha:
documentquerySelector('#container').style.background = 'red'
Aqui está uma rápida demonstração de alterar a cor da caixa a cada 0,5 s:
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>
Alterar o CSS de vários HTMLElement
Imagine que você gostaria de aplicar estilos CSS para mais de um elemento, por exemplo, fazer a cor de plano de fundo de todos os elementos com o nome da classe box
lightgreen
.Em seguida, você pode:
selecione os elementos com
.querySelectorAll
e desembrulhe-los em um objetoArray
com o desestruturação sintaxe:const elements = [...document.querySelectorAll('.box')]
um loop sobre a matriz com
.forEach
e aplicar a alteração para cada elemento:elements.forEach(element => element.style.background = 'lightgreen')
Aqui está a versão de 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>
Outro método
Se você deseja alterar várias propriedades de estilo de um elemento mais do que uma vez que você pode considerar o uso de outro método:link deste elemento para outro de classe em vez disso.
Supondo que você pode preparar os estilos de antemão, CSS, você pode alternar aulas acessando o classList
do elemento e chamar a toggle
função:
document.querySelector('.box').classList.toggle('orange')
.box {
width: 100px;
height: 100px;
}
.orange {
background: orange;
}
<div class='box'></div>
Lista de propriedades CSS em JavaScript
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
$(".class")[0].style.background = "blue";