Question

Comment puis-je définir la couleur d'arrière-plan CSS d'un élément HTML à l'aide de JavaScript ?

Était-ce utile?

La solution

En général, les propriétés CSS sont converties en JavaScript en les rendant camelCase sans aucun tiret.Donc background-color devient backgroundColor.

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

Autres conseils

Vous constaterez peut-être que votre code est plus maintenable si vous conservez tous vos styles, etc.en CSS et définissez/désactivez simplement les noms de classe en JavaScript.

Votre CSS serait évidemment quelque chose comme :

.highlight {
    background:#ff00aa;
}

Puis en JavaScript :

element.className = element.className === 'highlight' ? '' : 'highlight';
var element = document.getElementById('element');
element.style.background = '#FF00AA';

Ou, en utilisant un peu de jQuery :

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

Ajoutez cet élément de script à votre élément 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>

Tu peux essayer ça

var element = document.getElementById('element_id');
element.style.backgroundColor = "color or color_code";

Exemple.

var element = document.getElementById('firstname');
element.style.backgroundColor = "green";//Or #ff55ff

JSFIDDLE

Vous pouvez le faire avec JQuery :

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

Réponse de KISS :

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

Vous pouvez utiliser:

  <script type="text/javascript">
     Window.body.style.backgroundColor = "#5a5a5a";
  </script>
$('#ID / .Class').css('background-color', '#FF6600');

En utilisant jquery, nous pouvons cibler la classe ou l'identifiant de l'élément pour appliquer un arrière-plan CSS ou tout autre style.

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

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

il y a tellement de façons, je pense que c'est très facile et simple

Démo sur Plunker

vous pouvez utiliser

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

Changer le CSS d'un HTMLElement

Vous pouvez modifier la plupart des propriétés CSS avec JavaScript, utilisez cette instruction :

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

<selector>, <property>, <new style> sont tous String objets.

Habituellement, la propriété style aura le même nom que le nom réel utilisé en CSS.Mais chaque fois qu’il y aura plus d’un mot, ce sera camel case :Par exemple background-color est modifié avec backgroundColor.

La déclaration suivante définira le contexte de #container à la couleur rouge :

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

Voici une démo rapide changeant la couleur de la boîte toutes les 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>


Changer le CSS de plusieurs HTMLElement

Imaginez que vous souhaitiez appliquer des styles CSS à plusieurs éléments, par exemple définir la couleur d'arrière-plan de tous les éléments portant le nom de la classe. box lightgreen.Ensuite vous pouvez:

  1. sélectionnez les éléments avec .querySelectorAll et déballer-les dans un objet Array avec le syntaxe de déstructuration:

    const elements = [...document.querySelectorAll('.box')]
    
  2. boucle sur le tableau avec .forEach et appliquez la modification à chaque élément :

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

Voici la démo :

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>


Une autre méthode

Si vous souhaitez modifier plusieurs propriétés de style d'un élément plusieurs fois, vous pouvez envisager d'utiliser une autre méthode :liez plutôt cet élément à une autre classe.

En supposant que vous puissiez préparer les styles au préalable en CSS, vous pouvez basculer entre les classes en accédant au classList de l'élément et en appelant le toggle fonction:

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

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


Liste des propriétés CSS en JavaScript

Voici la liste complète:

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";
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top