JavaScript kullanarak bir HTML öğesinin CSS arka plan rengini nasıl ayarlayabilirim?
JavaScript kullanarak bir HTML öğesinin CSS arka plan rengini nasıl ayarlayabilirim?
Yanıtlar:
Genel olarak, CSS özellikleri, herhangi bir tire olmadan camelCase yapılarak JavaScript'e dönüştürülür. Böylece background-colorolur backgroundColor.
function setColor(element, color)
{
element.style.backgroundColor = color;
}
// where el is the concerned element
var el = document.getElementById('elementId');
setColor(el, 'green');
Tüm stillerinizi, vb. CSS'de tutarsanız ve JavaScript'te sınıf adlarını ayarlar / kaldırırsanız, kodunuzun daha iyi korunabileceğini görebilirsiniz.
CSS'niz açıkça şöyle bir şey olacaktır:
.highlight {
background:#ff00aa;
}
Ardından JavaScript'te:
element.className = element.className === 'highlight' ? '' : 'highlight';
Veya biraz jQuery kullanarak:
$('#fieldID').css('background-color', '#FF6600');
Bu komut dosyası öğesini body öğenize ekleyin:
<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>
Bunu deneyebilirsin
var element = document.getElementById('element_id');
element.style.backgroundColor = "color or color_code";
Misal.
var element = document.getElementById('firstname');
element.style.backgroundColor = "green";//Or #ff55ff
element.style.background-colorgeçerli bir JavaScript değil. Bu nedenle CSS özellikleri CamelCase'e dönüştürülür.
KISS Cevap:
document.getElementById('element').style.background = '#DD00DD';
document.getElementByClass('element').style.background = '#DD00DD';
$("body").css("background","green"); //jQuery
document.body.style.backgroundColor = "green"; //javascript
o kadar çok yol var ki bence çok kolay ve basit
$('#ID / .Class').css('background-color', '#FF6600');
Jquery kullanarak, css arka planını veya diğer stilleri uygulamak için öğenin sınıfını veya kimliğini hedefleyebiliriz
kullanabilirsiniz
$('#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
HTMLElementCSS özelliklerinin çoğunu JavaScript ile değiştirebilirsiniz, şu ifadeyi kullanın:
document.querySelector(<selector>).style[<property>] = <new style>
nerede <selector>, <property>, <new style>hepsi Stringnesneler.
Genellikle stil özelliği, CSS'de kullanılan gerçek adla aynı ada sahip olacaktır. Ancak birden fazla kelime olduğu zaman, bu deve durumu olacaktır: örneğin background-colorile değiştirilir backgroundColor.
Aşağıdaki ifade, arka planını #containerkırmızı renge ayarlayacaktır :
documentquerySelector('#container').style.background = 'red'
Her 0.5 saniyede bir kutunun rengini değiştiren hızlı bir demo:
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>
HTMLElementCSS stillerini birden fazla öğeye uygulamak istediğinizi düşünün, örneğin, sınıf adıyla tüm öğelerin arka plan rengini yapın box lightgreen. O zaman yapabilirsin:
yıkıcı sözdizimine sahip .querySelectorAllbir nesneye Arraysahip öğeleri seçin ve bunları açın :
const elements = [...document.querySelectorAll('.box')]ile dizi üzerinde döngü yapın .forEachve değişikliği her öğeye uygulayın:
elements.forEach(element => element.style.background = 'lightgreen')İşte 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>
Bir elemanın birden çok stil özelliğini değiştirmek istiyorsanız, başka bir yöntem kullanmayı düşünebilirsiniz: bunun yerine bu öğeyi başka bir sınıfa bağlayın.
CSS'de stilleri önceden hazırlayabileceğinizi varsayarsak classList, öğeye erişip toggleişlevi çağırarak sınıflar arasında geçiş yapabilirsiniz :
document.querySelector('.box').classList.toggle('orange')
.box {
width: 100px;
height: 100px;
}
.orange {
background: orange;
}
<div class='box'></div>
İşte tam 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
Basit bir js bunu çözebilir:
document.getElementById("idName").style.background = "blue";
$(".class")[0].style.background = "blue";