ฉันจะตั้งค่าสีพื้นหลัง CSS ขององค์ประกอบ HTML โดยใช้ JavaScript ได้อย่างไร
ฉันจะตั้งค่าสีพื้นหลัง CSS ขององค์ประกอบ HTML โดยใช้ JavaScript ได้อย่างไร
คำตอบ:
โดยทั่วไปคุณสมบัติ CSS จะถูกแปลงเป็น JavaScript โดยทำให้เป็น camelCase โดยไม่มีขีดกลาง ดังนั้นจะกลายเป็นbackground-color
backgroundColor
function setColor(element, color)
{
element.style.backgroundColor = color;
}
// where el is the concerned element
var el = document.getElementById('elementId');
setColor(el, 'green');
คุณอาจพบว่าโค้ดของคุณสามารถดูแลรักษาได้มากขึ้นหากคุณเก็บสไตล์ทั้งหมด ฯลฯ ไว้ใน CSS และเพียงแค่ตั้ง / ยกเลิกการตั้งชื่อคลาสใน JavaScript
เห็นได้ชัดว่า CSS ของคุณจะเป็นดังนี้:
.highlight {
background:#ff00aa;
}
จากนั้นใน JavaScript:
element.className = element.className === 'highlight' ? '' : 'highlight';
var element = document.getElementById('element');
element.style.background = '#FF00AA';
หรือใช้ jQuery เล็กน้อย:
$('#fieldID').css('background-color', '#FF6600');
เพิ่มองค์ประกอบสคริปต์นี้ในองค์ประกอบร่างกายของคุณ:
<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>
คุณสามารถลองสิ่งนี้
var element = document.getElementById('element_id');
element.style.backgroundColor = "color or color_code";
ตัวอย่าง.
var element = document.getElementById('firstname');
element.style.backgroundColor = "green";//Or #ff55ff
element.style.background-color
ไม่ใช่ JavaScript ที่ถูกต้อง นั่นเป็นเหตุผลที่คุณสมบัติ CSS ถูกแปลงเป็น CamelCase
คุณสามารถทำได้ด้วย JQuery:
$(".class").css("background","yellow");
KISS ตอบ:
document.getElementById('element').style.background = '#DD00DD';
document.getElementByClass('element').style.background = '#DD00DD';
คุณสามารถใช้ได้:
<script type="text/javascript">
Window.body.style.backgroundColor = "#5a5a5a";
</script>
$("body").css("background","green"); //jQuery
document.body.style.backgroundColor = "green"; //javascript
มีหลายวิธีที่ฉันคิดว่ามันง่ายและเรียบง่าย
$('#ID / .Class').css('background-color', '#FF6600');
เมื่อใช้ jquery เราสามารถกำหนดเป้าหมายคลาสหรือ Id ขององค์ประกอบเพื่อใช้พื้นหลัง css หรือสไตล์อื่น ๆ
คุณสามารถใช้ได้
$('#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
คุณสามารถเปลี่ยนคุณสมบัติ CSS ส่วนใหญ่ด้วย JavaScript ได้โดยใช้คำสั่งนี้:
document.querySelector(<selector>).style[<property>] = <new style>
ที่<selector>
, <property>
, <new style>
มีทั้งหมดString
วัตถุ
โดยปกติคุณสมบัติสไตล์จะมีชื่อเดียวกับชื่อจริงที่ใช้ใน CSS แต่เมื่อใดก็ตามที่มีคำนั้นมากกว่าหนึ่งคำก็จะเป็นกรณีอูฐเช่นbackground-color
เปลี่ยนด้วยbackgroundColor
มีการเปลี่ยนแปลงด้วย
คำสั่งต่อไปนี้จะกำหนดพื้นหลัง#container
เป็นสีแดง:
documentquerySelector('#container').style.background = 'red'
นี่คือตัวอย่างสั้น ๆ ที่เปลี่ยนสีของกล่องทุกๆ 0.5 วินาที:
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
ลองนึกภาพคุณต้องการที่จะใช้รูปแบบ CSS box
lightgreen
องค์ประกอบมากกว่าหนึ่งตัวอย่างเช่นทำให้สีพื้นหลังขององค์ประกอบทั้งหมดที่มีชื่อชั้น จากนั้นคุณสามารถ:
เลือกองค์ประกอบ.querySelectorAll
และแกะออกในวัตถุArray
ด้วยไวยากรณ์การทำลาย :
const elements = [...document.querySelectorAll('.box')]
วนซ้ำอาร์เรย์ด้วย.forEach
และใช้การเปลี่ยนแปลงกับแต่ละองค์ประกอบ:
elements.forEach(element => element.style.background = 'lightgreen')
นี่คือการสาธิต:
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>
หากคุณต้องการเปลี่ยนคุณสมบัติหลายสไตล์ขององค์ประกอบมากกว่าหนึ่งครั้งคุณอาจลองใช้วิธีอื่น: เชื่อมโยงองค์ประกอบนี้กับคลาสอื่นแทน
สมมติว่าคุณสามารถเตรียมสไตล์ไว้ล่วงหน้าใน CSS คุณสามารถสลับคลาสโดยเข้าถึงclassList
องค์ประกอบและเรียกใช้toggle
ฟังก์ชัน:
document.querySelector('.box').classList.toggle('orange')
.box {
width: 100px;
height: 100px;
}
.orange {
background: orange;
}
<div class='box'></div>
นี่คือรายการทั้งหมด:
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 ง่ายๆสามารถแก้ปัญหานี้ได้:
document.getElementById("idName").style.background = "blue";
$(".class")[0].style.background = "blue";