Pregunta

¿Cómo puedo ajustar el CSS color de fondo de un elemento HTML con JavaScript?

¿Fue útil?

Solución

En general, las propiedades CSS se convierten en JavaScript, haciendo de ellos camelCase sin guiones.Así background-color se convierte en backgroundColor.

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

Otros consejos

Usted puede encontrar su código es más fácil de mantener si usted mantiene todos sus estilos, etc.en CSS y solo set / unset nombres de clase en JavaScript.

Tu CSS, obviamente, sería algo como:

.highlight {
    background:#ff00aa;
}

A continuación, en JavaScript:

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

O, con un poco de jQuery:

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

Añadir este elemento de secuencia de comandos a su elemento del cuerpo:

<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>

Usted puede probar esto

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

Ejemplo.

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

JSFIDDLE

Usted puede hacerlo con JQuery:

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

BESO Respuesta:

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

Usted puede utilizar:

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

Mediante el uso de jquery podemos apuntar el elemento de la clase o Id para aplicar css de fondo o de cualquier otra actuación

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

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

muchas maneras hay creo que es muy fácil y simple

Demo En Plunker

puede utilizar

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

Cambiar el CSS de un HTMLElement

Usted puede cambiar la mayoría de las propiedades CSS con JavaScript, el uso de esta instrucción:

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

donde <selector>, <property>, <new style> son todos String objetos.

Generalmente, el estilo de la propiedad tendrá el mismo nombre que el nombre real utilizada en CSS.Pero cada vez que hay es más que una palabra, será camello caso:por ejemplo background-color se cambia con backgroundColor.

La siguiente declaración se establece el fondo de #container el color rojo:

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

He aquí una pequeña demostración de cambiar el color de la caja de 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>


Cambiar el CSS de múltiples HTMLElement

Imagina que te gustaría aplicar estilos CSS a más de un elemento, por ejemplo, hacer que el color de fondo de todos los elementos con el nombre de la clase box lightgreen.Entonces usted puede:

  1. seleccione los elementos con .querySelectorAll y desenvuelva en un objeto Array con el desestructuración de la sintaxis:

    const elements = [...document.querySelectorAll('.box')]
    
  2. recorrer el array con .forEach y aplicar el cambio a cada elemento:

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

Aquí está la 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>


Otro método

Si desea cambiar varias propiedades de estilo de un elemento más de una vez, usted puede considerar el uso de otro método:enlace de este elemento a otro de la clase en su lugar.

Suponiendo que usted puede preparar los estilos de antemano en CSS que se pueden alternar las clases mediante el acceso a la classList del elemento y llamar a la toggle función:

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

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


Lista de propiedades CSS JavaScript

Aquí está la 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";
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top