128

如何在 JavaScript 中使用 css 设置 HTML 元素的背景颜色?

4

17 回答 17

164

通常,CSS 属性通过使它们不带任何破折号的驼峰式大小写转换为 JavaScript。就这样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');
于 2008-08-06T12:25:54.920 回答
30

如果您将所有样式等都保留在 CSS 中,并且只在 JavaScript 中设置/取消设置类名,您可能会发现您的代码更易于维护。

你的 CSS 显然是这样的:

.highlight {
    background:#ff00aa;
}

然后在 JavaScript 中:

element.className = element.className === 'highlight' ? '' : 'highlight';
于 2008-08-19T11:59:40.470 回答
24
var element = document.getElementById('element');
element.style.background = '#FF00AA';
于 2008-08-06T12:25:13.800 回答
21

或者,使用一点 jQuery:

$('#fieldID').css('background-color', '#FF6600');
于 2008-08-06T13:23:42.247 回答
7

将此脚本元素添加到您的正文元素:

<body>
  <script type="text/javascript">
     document.body.style.backgroundColor = "#AAAAAA";
  </script>
</body>
于 2011-03-03T21:20:56.590 回答
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>

于 2015-04-17T16:07:45.950 回答
5

你可以试试这个

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

于 2015-09-03T12:21:03.320 回答
4

亲吻答案:

document.getElementById('element').style.background = '#DD00DD';
于 2013-03-01T23:57:53.427 回答
4

你可以用 JQuery 做到这一点:

$(".class").css("background","yellow");
于 2014-02-10T17:13:09.163 回答
3

您可以使用:

<script type="text/javascript">
  Window.body.style.backgroundColor = "#5a5a5a";
</script>
于 2014-01-05T12:51:06.763 回答
3
$("body").css("background","green"); //jQuery

document.body.style.backgroundColor = "green"; //javascript

有这么多方法,我认为这很容易和简单

Plunker 上的演示

于 2017-03-13T20:51:31.147 回答
3
$('#ID / .Class').css('background-color', '#FF6600');

通过使用 jquery,我们可以定位元素的类或 Id 以应用 css 背景或任何其他样式

于 2017-06-23T09:56:47.933 回答
1

您可以使用

$('#elementID').css('background-color', '#C0C0C0');
于 2014-04-11T01:34:55.530 回答
0

Javascript:

document.getElementById("ID").style.background = "colorName"; //JS ID

document.getElementsByClassName("ClassName")[0].style.background = "colorName"; //JS Class

查询:

$('#ID/.className').css("background","colorName") // One style

$('#ID/.className').css({"background":"colorName","color":"colorname"}); //Multiple style
于 2017-06-23T10:02:59.833 回答
0

更改 a 的 CSSHTMLElement

您可以使用 JavaScript 更改大部分 CSS 属性,使用以下语句:

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>


更改多个 CSSHTMLElement

想象一下,您想将 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>


JavaScript 中的 CSS 属性列表

以下是完整列表:

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
于 2018-06-07T19:51:07.130 回答
0

一个简单的js就可以解决这个问题:

document.getElementById("idName").style.background = "blue";
于 2020-01-20T08:38:10.603 回答
-1
$(".class")[0].style.background = "blue";
于 2015-11-11T08:44:51.483 回答