Vra

Hoe kan ek die CSS agtergrondkleur van 'n HTML-element met behulp van JavaScript?

Was dit nuttig?

Oplossing

In die algemeen, CSS eienskappe word omgeskakel na JavaScript deur hulle camelCase sonder enige strepe. So background-color word backgroundColor.

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

Ander wenke

Jy kan vind jou kode is meer onderhou as jy al jou style, ens in CSS en net Stel / ontstel klasname hou in JavaScript.

Jou CSS sou natuurlik iets soos:

.highlight {
    background:#ff00aa;
}

Toe ek in JavaScript:

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

Of, met behulp van 'n bietjie jQuery:

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

Voeg hierdie script element aan jou liggaam element:

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

Jy kan dit probeer

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

Voorbeeld.

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

JSFIDDLE

Jy kan dit doen met JQuery:

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

KISS Antwoord:

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

Jy kan gebruik:

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

Deur die gebruik van jQuery ons kan rig klas of id die element se css agtergrond of enige ander stylings van toepassing

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

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

so baie maniere is daar ek dink dit is baie maklik en eenvoudig

Demo Op Plunker

jy kan gebruik

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

Verandering van CSS van 'n HTMLElement

Jy kan die meeste van die CSS eienskappe met JavaScript verander, gebruik hierdie stelling:

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

waar <selector>, <property>, <new style> is almal String voorwerpe.

Gewoonlik, sal die eiendom styl dieselfde naam as die werklike naam gebruik in CSS het. Maar wanneer daar 'meer as een woord, sal dit kameel geval wees:. Byvoorbeeld background-color verander met backgroundColor

Die volgende verklaring sal die agtergrond van #container om die kleur rooi stel

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

Hier is 'n vinnige demo verander die kleur van die boks elke 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>


Verandering van CSS van verskeie HTMLElement

Verbeel jou jy wil CSS style van toepassing op meer as een element, byvoorbeeld, maak die agtergrond van al die elemente met die klas naam box lightgreen. Dan kan jy:

  1. Kies die elemente met .querySelectorAll en oop maak hulle in 'n voorwerp Array met die vernietigende sintaksis :

    const elements = [...document.querySelectorAll('.box')]
    
  2. lus oor die skikking met .forEach en die verandering aan elke element van toepassing:

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

Hier is die 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>


Nog 'n metode

As jy wil veelvuldige styl eienskappe van 'n element meer as een keer jy verander kan oorweeg om 'n ander metode:. Skakel hierdie element na 'n ander klas plaas

Wanneer jy kan die style vooraf voor te berei in CSS jy kan klasse wissel deur die toegang tot die classList van die element en die roeping van die toggle funksie:

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

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


Lys van CSS eienskappe in JavaScript

Hier is die volledige lys:

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";
Gelisensieer onder: CC-BY-SA met toeskrywing
Nie verbonde aan StackOverflow
scroll top