Comment définir la couleur d'arrière-plan CSS d'un élément HTML à l'aide de JavaScript?
Comment définir la couleur d'arrière-plan CSS d'un élément HTML à l'aide de JavaScript?
Réponses:
En général, les propriétés CSS sont converties en JavaScript en les rendant camelCase sans aucun tiret. Ainsi background-color
devient backgroundColor
.
function setColor(element, color)
{
element.style.backgroundColor = color;
}
// where el is the concerned element
var el = document.getElementById('elementId');
setColor(el, 'green');
Vous constaterez peut-être que votre code est plus facile à gérer si vous conservez tous vos styles, etc. en CSS et définissez / supprimez 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';
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>
Vous pouvez essayer ceci
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
element.style.background-color
n'est pas un JavaScript valide. C'est pourquoi les propriétés CSS sont converties en CamelCase.
Réponse KISS:
document.getElementById('element').style.background = '#DD00DD';
document.getElementByClass('element').style.background = '#DD00DD';
$("body").css("background","green"); //jQuery
document.body.style.backgroundColor = "green"; //javascript
il y a tellement de façons que je pense que c'est très facile et simple
$('#ID / .Class').css('background-color', '#FF6600');
En utilisant jquery, nous pouvons cibler la classe ou l'ID de l'élément pour appliquer un arrière-plan css ou tout autre style
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
HTMLElement
Vous pouvez modifier la plupart des propriétés CSS avec JavaScript, utilisez cette instruction:
document.querySelector(<selector>).style[<property>] = <new style>
où <selector>
, <property>
, <new style>
sont tous les String
objets.
Habituellement, la propriété de style aura le même nom que le nom réel utilisé dans CSS. Mais à chaque fois qu'il y aura plus d'un mot, ce sera le cas du chameau: par exemple background-color
on change avec backgroundColor
.
L'instruction suivante définira l'arrière-plan de #container
sur la couleur rouge:
documentquerySelector('#container').style.background = 'red'
Voici une démo rapide changeant la couleur de la boîte toutes les 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
Imaginez que vous souhaitiez appliquer des styles CSS à plusieurs éléments, par exemple, créer la couleur d'arrière-plan de tous les éléments avec le nom de la classe box
lightgreen
. Ensuite vous pouvez:
sélectionnez les éléments avec .querySelectorAll
et dépliez-les dans un objet Array
avec la syntaxe de déstructuration :
const elements = [...document.querySelectorAll('.box')]
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>
Si vous souhaitez modifier plusieurs fois les propriétés de style d'un élément, vous pouvez envisager d'utiliser une autre méthode: liez cet élément à une autre classe à la place.
En supposant que vous puissiez préparer les styles à l'avance dans CSS, vous pouvez basculer entre les classes en accédant au classList
de l'élément et en appelant la toggle
fonction:
document.querySelector('.box').classList.toggle('orange')
.box {
width: 100px;
height: 100px;
}
.orange {
background: orange;
}
<div class='box'></div>
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
Un simple js peut résoudre ceci:
document.getElementById("idName").style.background = "blue";
$(".class")[0].style.background = "blue";