Jak ustawić kolor tła CSS elementu HTML za pomocą JavaScript?
Jak ustawić kolor tła CSS elementu HTML za pomocą JavaScript?
Odpowiedzi:
Ogólnie rzecz biorąc, właściwości CSS są konwertowane na JavaScript poprzez nadanie im camelCase bez żadnych myślników. Tak background-color
się stanie backgroundColor
.
function setColor(element, color)
{
element.style.backgroundColor = color;
}
// where el is the concerned element
var el = document.getElementById('elementId');
setColor(el, 'green');
Może się okazać, że twój kod będzie łatwiejszy w utrzymaniu, jeśli zachowasz wszystkie swoje style itp. W CSS i po prostu ustawisz / usuniesz nazwy klas w JavaScript.
Twój CSS oczywiście wyglądałby tak:
.highlight {
background:#ff00aa;
}
Następnie w JavaScript:
element.className = element.className === 'highlight' ? '' : 'highlight';
Lub używając małego jQuery:
$('#fieldID').css('background-color', '#FF6600');
Dodaj ten element skryptu do elementu 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>
Możesz tego spróbować
var element = document.getElementById('element_id');
element.style.backgroundColor = "color or color_code";
Przykład.
var element = document.getElementById('firstname');
element.style.backgroundColor = "green";//Or #ff55ff
element.style.background-color
nieprawidłowy JavaScript. Dlatego właściwości CSS są konwertowane na CamelCase.
Odpowiedź KISS:
document.getElementById('element').style.background = '#DD00DD';
document.getElementByClass('element').style.background = '#DD00DD';
$("body").css("background","green"); //jQuery
document.body.style.backgroundColor = "green"; //javascript
jest tak wiele sposobów, myślę, że jest to bardzo łatwe i proste
$('#ID / .Class').css('background-color', '#FF6600');
Używając jquery, możemy kierować na klasę lub Id elementu, aby zastosować tło css lub inne style
możesz użyć
$('#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
Możesz zmienić większość właściwości CSS za pomocą JavaScript, użyj tej instrukcji:
document.querySelector(<selector>).style[<property>] = <new style>
gdzie <selector>
, <property>
, <new style>
są wszystkie String
obiekty.
Zwykle właściwość style będzie miała taką samą nazwę, jak rzeczywista nazwa używana w CSS. Ale ilekroć jest więcej niż jedno słowo, będzie to przypadek wielbłąda: na przykład background-color
jest zamieniony za pomocąbackgroundColor
.
Poniższa instrukcja ustawi tło #container
na kolor czerwony:
documentquerySelector('#container').style.background = 'red'
Oto krótkie demo zmieniające kolor pudełka co 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>
HTMLElement
Wyobraź sobie, że chcesz zastosować style CSS do więcej niż jednego elementu, na przykład nadać kolor tła wszystkim elementom o nazwie klasy box
lightgreen
. Następnie możesz:
wybierz elementy za pomocą .querySelectorAll
i rozpakuj je w obiekcie Array
o składni destrukturyzującej :
const elements = [...document.querySelectorAll('.box')]
pętla po tablicy za pomocą .forEach
i zastosuj zmianę do każdego elementu:
elements.forEach(element => element.style.background = 'lightgreen')
Oto 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>
Jeśli chcesz zmienić wiele właściwości stylu elementu więcej niż raz, możesz rozważyć użycie innej metody: zamiast tego połącz ten element z inną klasą.
Zakładając, że możesz wcześniej przygotować style w CSS, możesz przełączać klasy, uzyskując dostęp classList
do elementu i wywołując toggle
funkcję:
document.querySelector('.box').classList.toggle('orange')
.box {
width: 100px;
height: 100px;
}
.orange {
background: orange;
}
<div class='box'></div>
Oto pełna lista:
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
Prosty js może rozwiązać ten problem:
document.getElementById("idName").style.background = "blue";
$(".class")[0].style.background = "blue";