วิธีตั้งค่าสีพื้นหลัง CSS ของ HTML โดยใช้ JavaScript


คำตอบ:


155

โดยทั่วไปคุณสมบัติ CSS จะถูกแปลงเป็น JavaScript โดยทำให้เป็น camelCase โดยไม่มีขีดกลาง ดังนั้นจะกลายเป็นbackground-colorbackgroundColor

function setColor(element, color)
{
    element.style.backgroundColor = color;
}

// where el is the concerned element
var el = document.getElementById('elementId');
setColor(el, 'green');

3
ฉันต้องการเพิ่มสีที่เห็นได้ชัดว่าต้องอยู่ใน quotes element.style.backgroundColor = "color"; ตัวอย่างเช่น - element.style.backgroundColor = "orange"; คำตอบที่ดีเยี่ยม
Catto

ในการทดสอบ Selenium: ((IJavaScriptExecutor) WebDriver) .ExecuteScript ("arguments [0] .style.background = 'yellow';", webElement);
nexoma

@Catto ในกรณีนี้สีเป็นอาร์กิวเมนต์ของฟังก์ชันดังนั้นจึงไม่ควรอยู่ในเครื่องหมายคำพูด อย่างไรก็ตามคุณพูดถูกว่าโดยปกติหากตั้งค่าสีจะต้องมีเครื่องหมายอัญประกาศคู่ใน JS
Bharat Mallapur

29

คุณอาจพบว่าโค้ดของคุณสามารถดูแลรักษาได้มากขึ้นหากคุณเก็บสไตล์ทั้งหมด ฯลฯ ไว้ใน CSS และเพียงแค่ตั้ง / ยกเลิกการตั้งชื่อคลาสใน JavaScript

เห็นได้ชัดว่า CSS ของคุณจะเป็นดังนี้:

.highlight {
    background:#ff00aa;
}

จากนั้นใน JavaScript:

element.className = element.className === 'highlight' ? '' : 'highlight';

2
ฉันจะบอกว่ามันชัดเจนว่าจะวางไว้ที่ไหน - ที่ใดก็ได้หลังจาก HTML ที่คุณต้องการเปลี่ยน
TeeJay

1
สิ่งนี้ใช้ได้ในกรณีส่วนใหญ่ แต่ไม่ใช่ในกรณีที่มีการกำหนดสี (หรือแอตทริบิวต์ใด ๆ ) ในการกำหนดค่าหรือผู้ใช้ป้อนคุณไม่สามารถสร้างคลาส CSS สำหรับทุกสีที่เป็นไปได้)
Juan Mendes



7

เพิ่มองค์ประกอบสคริปต์นี้ในองค์ประกอบร่างกายของคุณ:

<body>
  <script type="text/javascript">
     document.body.style.backgroundColor = "#AAAAAA";
  </script>
</body>

6

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>


4

คุณสามารถลองสิ่งนี้

var element = document.getElementById('element_id');
element.style.backgroundColor = "color or color_code";

ตัวอย่าง.

var element = document.getElementById('firstname');
element.style.backgroundColor = "green";//Or #ff55ff

JSFIDDLE


1
element.style.background-colorไม่ใช่ JavaScript ที่ถูกต้อง นั่นเป็นเหตุผลที่คุณสมบัติ CSS ถูกแปลงเป็น CamelCase
CrazyIvan1974





3
$('#ID / .Class').css('background-color', '#FF6600');

เมื่อใช้ jquery เราสามารถกำหนดเป้าหมายคลาสหรือ Id ขององค์ประกอบเพื่อใช้พื้นหลัง css หรือสไตล์อื่น ๆ


1

คุณสามารถใช้ได้

$('#elementID').css('background-color', '#C0C0C0');

นี่คือ jquery ไม่ใช่ javascript
Vignesh Subramanian

@vignesh jQuery เป็น JavaScript -__-
Novocaine

@Novocaine jQuery เขียนโดยใช้ JavaScript ใช่ แต่ยังคง $ จะใช้งานไม่ได้เว้นแต่คุณจะรวมไลบรารี jQuery นั้นไว้;)
Vignesh Subramanian

0

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

0

การเปลี่ยน CSS ของไฟล์ 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>


การเปลี่ยน CSS ของหลาย ๆ HTMLElement

ลองนึกภาพคุณต้องการที่จะใช้รูปแบบ CSS box lightgreenองค์ประกอบมากกว่าหนึ่งตัวอย่างเช่นทำให้สีพื้นหลังขององค์ประกอบทั้งหมดที่มีชื่อชั้น จากนั้นคุณสามารถ:

  1. เลือกองค์ประกอบ.querySelectorAllและแกะออกในวัตถุArrayด้วยไวยากรณ์การทำลาย :

    const elements = [...document.querySelectorAll('.box')]
  2. วนซ้ำอาร์เรย์ด้วย.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>


รายการคุณสมบัติ CSS ใน JavaScript

นี่คือรายการทั้งหมด:

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


-1
$(".class")[0].style.background = "blue";

มีคำตอบที่ถูกต้องเพียงพอสำหรับคำถามนี้และคำตอบนี้ไม่ได้มีอะไรดีไปกว่าคำตอบอื่น ๆ
Novocaine

ดังที่ Novocaine กล่าวว่ามีคำตอบมากมายที่นี่ แต่ในอนาคตโปรดพิจารณาแก้ไขโพสต์ของคุณเพื่อเพิ่มคำอธิบายเพิ่มเติมว่าโค้ดของคุณใช้ทำอะไรและทำไมถึงแก้ปัญหาได้ คำตอบที่ส่วนใหญ่มีเพียงรหัส (แม้ว่าจะใช้งานได้) มักจะไม่ช่วยให้ OP เข้าใจปัญหาของพวกเขา
SuperBiasedMan
โดยการใช้ไซต์ของเรา หมายความว่าคุณได้อ่านและทำความเข้าใจนโยบายคุกกี้และนโยบายความเป็นส่วนตัวของเราแล้ว
Licensed under cc by-sa 3.0 with attribution required.