Wie kann ich die CSS-Hintergrundfarbe eines HTML-Elements mit JavaScript festlegen?
Wie kann ich die CSS-Hintergrundfarbe eines HTML-Elements mit JavaScript festlegen?
Antworten:
Im Allgemeinen werden CSS-Eigenschaften in JavaScript konvertiert, indem sie ohne Bindestriche camelCase werden. So background-color
wird backgroundColor
.
function setColor(element, color)
{
element.style.backgroundColor = color;
}
// where el is the concerned element
var el = document.getElementById('elementId');
setColor(el, 'green');
Möglicherweise ist Ihr Code besser zu warten, wenn Sie alle Ihre Stile usw. in CSS behalten und nur Klassennamen in JavaScript festlegen / deaktivieren.
Ihr CSS wäre offensichtlich so etwas wie:
.highlight {
background:#ff00aa;
}
Dann in JavaScript:
element.className = element.className === 'highlight' ? '' : 'highlight';
Oder mit ein wenig jQuery:
$('#fieldID').css('background-color', '#FF6600');
Fügen Sie dieses Skriptelement Ihrem Körperelement hinzu:
<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>
Sie können dies versuchen
var element = document.getElementById('element_id');
element.style.backgroundColor = "color or color_code";
Beispiel.
var element = document.getElementById('firstname');
element.style.backgroundColor = "green";//Or #ff55ff
element.style.background-color
ist kein gültiges JavaScript. Aus diesem Grund werden CSS-Eigenschaften in CamelCase konvertiert.
KISS Antwort:
document.getElementById('element').style.background = '#DD00DD';
document.getElementByClass('element').style.background = '#DD00DD';
$("body").css("background","green"); //jQuery
document.body.style.backgroundColor = "green"; //javascript
Es gibt so viele Möglichkeiten, dass ich denke, dass es sehr einfach und unkompliziert ist
$('#ID / .Class').css('background-color', '#FF6600');
Mit jquery können wir auf die Klasse oder ID des Elements abzielen, um den CSS-Hintergrund oder andere Stile anzuwenden
Sie können verwenden
$('#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
Sie können die meisten CSS-Eigenschaften mit JavaScript ändern. Verwenden Sie diese Anweisung:
document.querySelector(<selector>).style[<property>] = <new style>
wo <selector>
, <property>
, <new style>
sind alle String
Objekte.
Normalerweise hat die Stileigenschaft denselben Namen wie der in CSS verwendete tatsächliche Name. Aber wenn es mehr als ein Wort gibt, wird es ein Kamelfall sein: zum Beispiel background-color
wird mit geändert backgroundColor
.
Die folgende Anweisung setzt den Hintergrund #container
auf die Farbe Rot:
documentquerySelector('#container').style.background = 'red'
Hier ist eine kurze Demo, in der alle 0,5 Sekunden die Farbe der Box geändert wird:
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
Stellen Sie sich vor, Sie möchten CSS-Stile auf mehr als ein Element anwenden, z. B. die Hintergrundfarbe aller Elemente mit dem Klassennamen festlegen box
lightgreen
. Dann kannst du:
.querySelectorAll
Wählen Sie die Elemente mit aus und wickeln Sie sie in ein Objekt Array
mit der Destrukturierungssyntax aus :
const elements = [...document.querySelectorAll('.box')]
Durchlaufen Sie das Array mit .forEach
und wenden Sie die Änderung auf jedes Element an:
elements.forEach(element => element.style.background = 'lightgreen')
Hier ist 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>
Wenn Sie mehrere Stileigenschaften eines Elements mehrmals ändern möchten, können Sie eine andere Methode verwenden: Verknüpfen Sie dieses Element stattdessen mit einer anderen Klasse.
Angenommen, Sie können die Stile zuvor in CSS vorbereiten, können Sie Klassen umschalten, indem Sie auf classList
das Element zugreifen und die toggle
Funktion aufrufen :
document.querySelector('.box').classList.toggle('orange')
.box {
width: 100px;
height: 100px;
}
.orange {
background: orange;
}
<div class='box'></div>
Hier ist die vollständige Liste:
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
Ein einfaches js kann dies lösen:
document.getElementById("idName").style.background = "blue";
$(".class")[0].style.background = "blue";