Bagaimana cara mengatur warna latar belakang CSS dari elemen HTML menggunakan JavaScript?
Bagaimana cara mengatur warna latar belakang CSS dari elemen HTML menggunakan JavaScript?
Jawaban:
Secara umum, properti CSS diubah menjadi JavaScript dengan menjadikannya camelCase tanpa tanda hubung. Jadi background-color
jadilah backgroundColor
.
function setColor(element, color)
{
element.style.backgroundColor = color;
}
// where el is the concerned element
var el = document.getElementById('elementId');
setColor(el, 'green');
Anda mungkin menemukan kode Anda lebih dapat dipelihara jika Anda menyimpan semua gaya Anda, dll. Di CSS dan hanya menyetel / tidak menyetel nama kelas di JavaScript.
CSS Anda jelas akan menjadi seperti ini:
.highlight {
background:#ff00aa;
}
Kemudian di JavaScript:
element.className = element.className === 'highlight' ? '' : 'highlight';
Atau, gunakan sedikit jQuery:
$('#fieldID').css('background-color', '#FF6600');
Tambahkan elemen skrip ini ke elemen tubuh Anda:
<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>
Anda bisa mencobanya
var element = document.getElementById('element_id');
element.style.backgroundColor = "color or color_code";
Contoh.
var element = document.getElementById('firstname');
element.style.backgroundColor = "green";//Or #ff55ff
element.style.background-color
bukan JavaScript yang valid. Itu sebabnya properti CSS diubah menjadi CamelCase.
KISS Jawaban:
document.getElementById('element').style.background = '#DD00DD';
document.getElementByClass('element').style.background = '#DD00DD';
$("body").css("background","green"); //jQuery
document.body.style.backgroundColor = "green"; //javascript
begitu banyak cara yang menurut saya sangat mudah dan sederhana
$('#ID / .Class').css('background-color', '#FF6600');
Dengan menggunakan jquery kita dapat menargetkan class atau Id elemen untuk menerapkan background css atau stylings lainnya
kamu bisa memakai
$('#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
Anda dapat mengubah sebagian besar properti CSS dengan JavaScript, gunakan pernyataan ini:
document.querySelector(<selector>).style[<property>] = <new style>
di mana <selector>
, <property>
, <new style>
semua String
benda.
Biasanya, properti style akan memiliki nama yang sama dengan nama sebenarnya yang digunakan di CSS. Tetapi jika ada lebih dari satu kata, itu akan menjadi kasus unta: misalnya background-color
diganti denganbackgroundColor
.
Pernyataan berikut akan menyetel latar belakang #container
menjadi warna merah:
documentquerySelector('#container').style.background = 'red'
Berikut demo singkat mengubah warna kotak setiap 0,5 detik:
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
Bayangkan Anda ingin menerapkan gaya CSS ke lebih dari satu elemen, misalnya membuat warna latar belakang semua elemen dengan nama kelas box
lightgreen
. Maka kamu bisa:
pilih elemen dengan .querySelectorAll
dan buka bungkusnya dalam sebuah objek Array
dengan sintaksis yang merusak :
const elements = [...document.querySelectorAll('.box')]
ulangi array dengan .forEach
dan terapkan perubahan ke setiap elemen:
elements.forEach(element => element.style.background = 'lightgreen')
Berikut demo nya:
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>
Jika Anda ingin mengubah beberapa properti gaya dari sebuah elemen lebih dari sekali, Anda dapat mempertimbangkan untuk menggunakan metode lain: tautkan elemen ini ke kelas lain sebagai gantinya.
Dengan asumsi Anda dapat mempersiapkan gaya sebelumnya di CSS, Anda dapat beralih kelas dengan mengakses classList
elemen dan memanggil toggle
fungsi:
document.querySelector('.box').classList.toggle('orange')
.box {
width: 100px;
height: 100px;
}
.orange {
background: orange;
}
<div class='box'></div>
Berikut daftar lengkapnya:
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
Js sederhana bisa menyelesaikan ini:
document.getElementById("idName").style.background = "blue";
$(".class")[0].style.background = "blue";